扩容的大逻辑跟前面一样。但是需要注意,vector里面每个位置存的是一个一个的桶,当swap后,newHT出了作用域就会调用析构,此时只会销毁每个位置,而不会销毁每个桶,所以需要我们自己写出析构函数。 上面的扩容方式,new了多少个节点,就得销毁多少个节点,所以不太好,下面是另一种方式: 重新开一个vector,将旧表里的桶依次取出放到新表对应的位置上,然后销毁...
x) ^ hash<int>()(p.y); } }; int main() { unordered_map<Point, string, PointHash> pointMap; pointMap[{1, 2}] = "Point(1, 2)"; pointMap[{3, 4}] = "Point(3, 4)"; for (const auto& pair : pointMap) { cout << pair.second << endl; // 输出 Point(1, 2), Point...
unordered_map内部维护一个“桶数组”,每个桶是一个链表(或链式哈希结构): 1. 先用哈希函数(默认是std::hash)计算键的哈希值。 2. 通过哈希值对桶数取模,定位到具体桶。 3. 在桶链表中查找对应的键(通过operator==比较)。 4. 找到则返回对应值,找不到则插入新元素。 哈希冲突时,多个键落在同一桶,链表...
int main() { std::unordered_map<std::string, int> scoreMap; scoreMap["Zhang"] = 85; scoreMap["Li"] = 92; scoreMap["Wang"] = 78; // 遍历时输出顺序不确定 for (constauto& student : scoreMap) { std::cout << student.first << ": " << student.second << std::endl; } retu...
1 vector<pair<int, string>> myVector = {{1, "one"}, {2, "two"}, {3, "three"}}; 2 unordered_map<int, string> mymap(myVector.begin(), myVector.end()); (4)使用给定的哈希函数和相等比较函数构造unordered_map: 1 struct myHashFunction { 2 size_t operator()(const int& key) co...
HashFunc和上面讲的一样,主要作用是如果key为其他不是size_t的类型将它们强转成size_t和若为string则通过哈希函数转化成size_t,这种方法就是泛型编程的一种。 闭散列: 闭散列,又称开放定址法,也就是上面提到的单纯使用顺序表的方法来实现哈希表,它应对哈希冲突的方法是如果哈希表未被装满,说明在哈希表中必然还...
#include<iostream>#include<map>#include<unordered_map>#include<chrono>#include<string>#include<vector>#include<random>// 计时辅助函数template<typenameFunc>longlongtimeOperation(Func func){autostart = std::chrono::high_resolution_clock::now();func();autoend = std::chrono::high_resolution_clock:...
#include<iostream>#include<string>#include<unordered_map>// 辅助函数,将多级键字符串转换为单一键std::stringflatten_key(conststd::vector<std::string>&keys,conststd::string&delimiter="."){std::string result;for(size_t i=0;i<keys.size();++i){result+=keys[i];if(i<keys.size()-1)result...
#include<vector> using namespace std; template<class K> struct HashFunc { size_t operator()(const K& key) { return size_t key; } }; template<> struct HashFunc<string> { size_t operator()(const string& s) { size_t hash = 0; ...
#include <string> #include <vector> #include <unordered_map> #include <functional> // std::hash class MyClass { public: std::vector<int> data; MyClass(const std::vector<int>& d) : data(d) {} bool operator==(const MyClass& oth...