C++ 之 unordered_map——哈希表
#include#include #include using namespace std; class Myclass { public: int first; vector<int> second; // 重载等号,判断两个Myclass类型的变量是否相等 bool operator== (const Myclass &other) const { return first == other.first && second == other.second; } }; // 实现Myclass类的hash函数 namespace std { template <> struct hash { size_t operator()(const Myclass &k) const { int h = k.first; for (auto x : k.second) { h ^= x; } return h; } }; } int main() { unordered_map double> S; Myclass a = { 2, {3, 4} }; Myclass b = { 3, {1, 2, 3, 4} }; S[a] = 2.5; S[b] = 3.123; cout << S[a] << ' ' << S[b] << endl; return 0; }