Files
Data-Structure/STL/STL-unordered_map/unordered_map.cpp
2025-08-13 17:54:58 +08:00

41 lines
1.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
class hashdef{
public:
//template<class T>不太好分类型就直接用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<int>(x)*31 + seed;
hash %= 1009;
}
return hash;
}
};
int main(){
hashdef a;
unordered_map<string, string, hashdef> m1{make_pair("1","111")};
unordered_map<string, string> 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
*/