#include #include #include using namespace std; class hashdef{ public: //template,不太好分类型,就直接用string了 size_t operator()(const string& a) const{//这里必须有const,在hash内部会把其当const调用 //同样不能有static,调用需要用到this int hash; int seed = 114514; for(char x : a){ hash += static_cast(x)*31 + seed; hash %= 1009; } return hash; } }; int main(){ hashdef a; unordered_map m1{make_pair("1","111")}; unordered_map m2; m1.insert({make_pair("2","222"),make_pair("3","333"),make_pair("6","666"),make_pair("5","555")}); //下面首先查看哈希值 cout << a("1") << " " << a("2") << " " << a("3") << " " << a("5") << " " << a("6") << endl; m1.rehash(1000);//重新设置桶的个数为1009,配合hash(此时会重新计算所有hash) m2.max_load_factor(0.7f);//重新设置-控制扩容-负载因子=元素个数/桶个数,这里是平均每个桶最多0.7个元素 cout << "bucket_count: " << m1.bucket_count() << endl;//hashtable_policy.h中的质数表跳转到最近的大于n的数 cout << m1.max_load_factor() << " " << m1.load_factor() << endl; m1["7"] = "777"; cout << m1.at("6") << " " << m1["5"] << " " << m1.find("6")->second << endl; return 0; } /* 1007 29 60 122 153 bucket_count: 1031 1 0.00484966 666 555 666 */