map的key可以是struct,但是因为map底层是红黑树,是有序的,因此struct内必须重载<.unordered_map的key不能是struct.
【例1】:map
#include <iostream>
#include <map>
using namespace std;
struct stone {
int a;
int b;
int c;
int d;
stone(int e, int f, int g, int h) :a(e), b(f), c(g), d(h) {}
bool operator< (const stone& s) const
{
return a < s.a;
}
};
int main()
{
map<stone, int> ma;
stone s(1, 2, 3, 4);
ma.insert(make_pair(s, 2));
auto it = ma.find(s);
if (it != ma.end())
{
cout << it->second << endl;
}
return 0;
}
【例2】:unordered_map
#include <iostream>
#include <unordered_map>
using namespace std;
struct stone {
int a;
int b;
int c;
int d;
stone(int e, int f, int g, int h) :a(e), b(f), c(g), d(h) {}
};
int main()
{
unordered_map<stone, int> ma;
stone s(1, 2, 3, 4);
ma.insert(make_pair(s, 2));
auto it = ma.find(s);
if (it != ma.end())
{
cout << it->second << endl;
}
system("pause");
return 0;
}
报错: