Добавил:
Hist
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз:
Предмет:
Файл:Программы c++ (сортировка, хэширование) / 3 / my3(example)
.cpp#include <iostream>
#include <stdio.h>
#include <string.h>
/* Максимальная длина ключа */
#define len 6
/* Кол-во строк в хэш-таблице */
#define n 20
using namespace std;
/* хэширование простым числом */
int simp(char s[])
{
int i = 0, sum = 0;
while (s[i] != '\0') {
sum = sum + s[i];
i++;
}
return (sum % 19);
}
/* добавление ключа в хэш-таблицу */
void addtab(char hash[][len], char s[])
{
int key;
key = simp(s);
printf("key1 = %d\n", key);
if(strcmp(hash[key],s)==0)
{ printf("yze est");
goto M;}
if (hash[key][0] != 0) {
while(hash[key][0] != 0)
if (++key == 20)
key = 0;
printf("key2 = %d\n", key);
}
strcpy(hash[key], s);
M:
getchar();
}
/* вывод таблицы */
void outtab(char hash[][len])
{
int i;
cout << "Tablica: " << endl;
for (i = 0; i < n; i++)
cout << i << " " << hash[i] << endl;
cout << endl;
getchar();
}
/* поиск ключа */
int find(char hash[][len], char s[])
{
int key, m;
key = simp(s);
if (strcmp(hash[key], s) == 0)
return key;
m = key;
key = key + 1;
while ((key != m) && (strcmp(hash[key], s) != 0))
if (++key == n)
key = 0;
if (key == m)
return -1;
return key;
}
/* удаление ключа */
void del(char hash[][len], char s[])
{
int a;
a = find(hash, s);
if (a >= 0)
hash[a][0] = '\0';
else
printf("Net takogo klucha");
}
int main(void)
{
char hash[n][len], s[len], key;
int i, a, b;
a = 0;
for (i = 0; i < n; i++)
hash[i][0] = 0;
cout << "-----------" << endl;
cout << "0. Dobavit kluch" << endl;
cout << "1. Naiti kluch" << endl;
cout << "2. Udalit kluch" << endl;
cout << "3. Vyvod tablicy" << endl;
cout << "4. Vyxod" << endl;
cout << "-----------" << endl;
while (1) {
cin >> key;
switch (key) {
case '0' : {
if (a < n) {
cout << "Vvedite kluch: " << endl;
scanf("%s", s);
addtab(hash, s);
a = a + 1;
} else {
cout << "Tablica perepolnena" << endl;
getchar();
}
break;
}
case '1' : {
printf("Vvedite kluch: ");
scanf("%s", s);
b = find(hash, s);
if (b >= 0)
cout << "Adres = " << b << endl;
else
cout << "Net takogo klucha" << endl;
getchar();
break;
}
case '2' : {
printf("Vvedite kluch: ");
scanf("%s", s);
fflush(stdin);
del(hash, s);
a = a - 1;
break;
}
case '3' : {
outtab(hash);
break;
}
case '4' : {
//exit(1);
return 1;
}
default:
break;
}
}
return 0;
}
Соседние файлы в папке 3