面试中问到了一个问题,定义一个map<A,int>,key是一个类,value是一个int型值,问这个类有什么限制吗?ios
当时没想出来,回头本身试的时候确实编译不过,报的错误是面试
error: no match for ‘operator<’ (operand types are ‘const A’ and ‘const A’)
{ return __x < __y; }函数
后来想了想,换成结构体呢,结果报错也是同样,以后就忽然想到map它是内部有序,作了排序机制的,因此你得定个规则让它有序,因此得重载operator < 运算符函数,而后写个规则给它(map也有无序的,unordered_map)。spa
写个例子:code
1 #include <iostream> 2 #include <map> 3 using namespace std; 4 5 /*map内部有排序机制,它是有序的,当map存结构体或者存类的时候,要重载operator < 运算符函数 6 */ 7 8 class A{ 9 int id; 10 string name; 11 public: 12 virtual void test(){ 13 cout << "A::test()" << endl; 14 } 15 bool operator < (const A &a) const 16 { 17 return id < a.id; 18 } 19 }; 20 21 struct B{ 22 int id; 23 string name; 24 B(){} 25 B(int x,string y):id(x),name(y){} 26 bool operator < (const B &a) const 27 { 28 return id < a.id; 29 } 30 }; 31 32 int main(){ 33 //map放类 34 map<A,int> tmap; 35 A a; 36 int num = 10; 37 tmap[a] = num; 38 39 /*--------------------------------------------------------------------------------*/ 40 //map放结构体 41 // map<B,int> bmap; 42 // for (int i = 0; i < 10; i++) { 43 // bmap.insert(pair<B, int>(B(i,"name"+i),i)); 44 // } 45 46 // for (auto it = bmap.begin(); it != bmap.end(); ++it) { 47 // cout << it->first.name << "-->" << it->second << endl; 48 // } 49 50 return 0; 51 }
OK!这样问题就解决了blog