我在设置比较时遇到了困难。
以下是我的问题示例,我的代码错误地假设{1,2} = {2,1}:http://ideone.com/i7huL
#include <iostream>
#include <map>
using namespace std;
struct myStruct {
int a;
int b;
bool operator<(const myStruct& rhs) const {
return rhs.a < this->a && rhs.b < this->b;
}
};
int main() {
std::map <myStruct, int> mymap ;
myStruct m1={1,2};
myStruct m2={2,1};
mymap.insert(make_pair(m1,3));
std::map<myStruct, int>::iterator it1 = mymap.find(m1);
std::map<myStruct, int>::iterator it2 = mymap.find(m2);
cout << it1->second << it2->second;
// here it1->second=it2->second=3, although I would have expected it2 to be equal to map.end().
}
我可以使用||代替&&,但我不确定这是否是正确的方法。我只想实现operator<,以便我能够在我的映射中找到对象,而没有任何错误发生,就像我链接的代码一样。
谢谢。