diff --git a/STL/STL-unordered_map/unordered_map.cpp b/STL/STL-unordered_map/unordered_map.cpp new file mode 100644 index 0000000..a056fce --- /dev/null +++ b/STL/STL-unordered_map/unordered_map.cpp @@ -0,0 +1,40 @@ +#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 +*/ diff --git a/STL/STL-unordered_map/unordered_multimap.cpp b/STL/STL-unordered_map/unordered_multimap.cpp new file mode 100644 index 0000000..a390606 --- /dev/null +++ b/STL/STL-unordered_map/unordered_multimap.cpp @@ -0,0 +1,20 @@ +//用法和unordered_map - multimap一致 +#include +#include +using namespace std; +int main(){ + unordered_multimap m; + m.insert({make_pair(1,111), make_pair(2,222), make_pair(3,333), make_pair(8,888), make_pair(6,666), make_pair(5,555)}); + m.insert({make_pair(1,11), make_pair(2,22), make_pair(1,1)}); + cout << m.count(1) << " " << m.find(1)->first << "," << m.find(1)->second << endl; + m.erase(m.find(1)); + cout << m.count(1) << " " << m.find(1)->first << "," << m.find(1)->second << endl; + m.erase(1); + cout << m.count(1) << endl; + return 0; +} +/* +3 1,1 +2 1,11 +0 +*/