#include #include #include using namespace std; unsigned hash(const string&); const unsigned NumberOfBuckets = 10; int main() { string animals[NumberOfBuckets] = {"monkey","dog","cat","horse","pig","goat","hippo","dinosaur","walrus","manatee"}; string* ptr2strings[NumberOfBuckets] = {nullptr}; for (auto i = 0u; i < NumberOfBuckets; i++) { auto index = ::hash(animals[i]); // if the index is unused, use it if (ptr2strings[index] == nullptr) { ptr2strings[index] = new string(animals[i]); } else { cout << "Can't store " << animals[i] << ". Bucket " << index << " is already taken\n"; } } for (auto i = 0u; i < NumberOfBuckets; i++) { cout << i << ' ' << (ptr2strings[i] ? *ptr2strings[i] : "" )<< endl; } } unsigned hash(const string& str) { static string alphabet = "abcdefghijklmnopqrstuvwxyz"; size_t pos; unsigned sum = 0; for (auto i = 0u; i < str.size(); i++) { pos = alphabet.find(tolower(str[i])); sum += pos; } return sum % NumberOfBuckets; }