我无法正确设置比较.这是我的问题的一个示例,我的代码错误地假设{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().
}
Run Code Online (Sandbox Code Playgroud)
我可以用|| 而不是&&,但我不确定这是正确的方法.我只想让operator <以我能够在地图中找到对象的方式实现,而不会出现任何错误,就像我链接到的代码中的情况一样.
谢谢.
是的,这个运算符实现没有多大意义.我建议:
bool operator<(const myStruct& rhs) const {
return rhs.a < this->a || (rhs.a == this->a && rhs.b < this->b);
}
Run Code Online (Sandbox Code Playgroud)
bool operator<(const myStruct& rhs) const {
if (a < rhs.a) return true;
if (a == rhs.a) return b < rhs.b;
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果您正在寻找对许多数据成员的概括,那么使用C++ 11 std :: tie就有一个很好的例子:
struct S {
int n;
std::string s;
float d;
bool operator<(const S& rhs) const {
return std::tie(n, s, d) < std::tie(rhs.n, rhs.s, rhs.d);
}
};
Run Code Online (Sandbox Code Playgroud)
问题是您的操作员没有定义严格的弱排序.仔细考虑您的例子,{1,2}
并将{2,1}
在您的运营商中落实.假设X = {1,2}
,和Y = {2,1}
.
X <Y?1 <2 AND 2 <1?不,因此X不小于Y.
Y <X?2 <1 AND 1 <2?不,因此Y不小于X.
所以,如果X不小于Y,而Y不小于X,那还剩下什么?他们是平等的.
你需要选择你的结构的成员之一,无论是a
或者b
是主要的比较.如果主要比较结果相同,那么您才会检查次要比较.就像你按字母顺序排列一样.首先你检查第一个字母,只有它们相等,你才能继续下一个字母.Hans Passant就是一个例子.
对于您的运营商来说,这是一个更严重的问题示例.我上面给出的那个不一定是坏的,因为也许你想 {1,2}
被认为是平等的{2,1}
.根本问题是通过这样的一组价值来实现:考虑X = {1,1}, Y = {1,2}, Z = {2,2}
对于你的算子,X最终小于Z,因为1小于2.但X出来等于Y,Y出来等于Z.为了坚持严格的弱排序,如果X = Y,和Y = Z,那么X应该等于Z.但是在这种情况并非如此.
归档时间: |
|
查看次数: |
24922 次 |
最近记录: |