自定义结构体作为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> 则不行。这点需要注意。
##################################
对于map来说, key必须是有序的, 也就是说, key与key之间必须能比较, 所以需要重载<号, 因此, 上述程序错误, 应该改为:
#include <iostream>
#include <string>
#include <map>
using namespace std;
struct Info
{
string name;
int score;
bool operator< (const Info &x) const
{
return score < x.score;
}
};
int main()
{
Info a, b;
a.name = "eric";
a.score = 90;
b.name = "cat";
b.score = 85;
map<Info, int> m;
m[a] = 1;
m[b] = 2;
map<Info, int>::iterator it;
for(it = m.begin(); it != m.end(); it++)
{
cout << it->first.name << endl;
}
return 0;
}
运行正确, 结果为:
cat
eric
OK, 本文先讨论到这里, 关键是要对map的“关键字有序”有足够的认识。