#include<stdio.h>
#include<string>
int int_func(int key, int table_len)
{
return key % table_len;
}
int string_func(std::string str, int table_len)
{
int sum = 0;
for (int i = 0; i < str.length(); i++)
{
sum += str[i];
}
return sum % table_len;
}
int main()
{
const int TABLE_LEN=10;
int hash_map[TABLE_LEN] = { 0 };
hash_map[int_func(999995, TABLE_LEN)]++;
hash_map[int_func(5, TABLE_LEN)]++;
hash_map[string_func("abc", TABLE_LEN)]++;
hash_map[string_func("bac", TABLE_LEN)]++;
for (int i = 0; i < 10; i++)
{
printf("hash_map[%d]=%d\n", i, hash_map[i]);
}
}
运行结果为:
hash_map[0]=0
hash_map[1]=0
hash_map[2]=0
hash_map[3]=0
hash_map[4]=2
hash_map[5]=2
hash_map[6]=0
hash_map[7]=0
hash_map[8]=0
hash_map[9]=0