自定义结构体作为C/C++中的map,或是unordered_map的key值:
/**
* self defined struct as the key of map in c++
*/
struct K {
int n1, n2;
K(int i, int j): n1(i), n2(j) {}
// the operator < defines the operation used in map
friend bool operator < (const struct K &k1, const struct K &k2);
};
inline bool operator < (const struct K &k1, const struct K &k2) {
return k1.n1 < k2.n1 || (k1.n1==k2.n1 && k1.n2<k2.n2);
}
void test() {
map<K, int> m;
map<K, int>::iterator it;
K k1(1, 1);
m.insert(make_pair(k1, 2)); // insert the value
it = m.find(k1);
if (it!=m.end()) cout << it->second << endl; // fetch the value
}
需要注意的是,当 struct K 实习重载了operator < 时,只有 map<K, int> 等以 K 为key才可以调用重载后的 operator <。
如果是遇到 map<K*, int> 则不行。这点需要注意。