我有以下的C++代码:
#include <set>
#include <string>
#include <iostream>
using namespace std;
class Pair {
public:
string lhs;
string rhs;
Pair();
Pair( string l, string r ) {
lhs=l;
rhs=r;
};
};
struct compare {
bool operator()(const Pair& a, const Pair& b) const{
if ( ( a.lhs == b.lhs && a.rhs == b.rhs ) || ( a.lhs == b.rhs && a.rhs == b.lhs ) ) {
cout << "MATCH" << endl;
}
return ( a.lhs == b.lhs && a.rhs == b.rhs ) || ( a.lhs == b.rhs && a.rhs == b.lhs );
}
};
int main () {
set<Pair, compare > s;
Pair p( string("Hello"), string("World") );
s.insert(p);
cout << s.size() << "\n";
Pair q( string("World"), string("Hello") );
s.insert(q);
cout << s.size() << "\n";
compare cmp;
cout << cmp( p, q );
return 0;
}
调用编译后的代码会产生以下结果:
1
MATCH
MATCH
2
MATCH
一些原因导致集合s最终包含了两个被比较器认为是相同的Pair p和q。为什么会这样呢?
非常感谢您的帮助!
更新:感谢大家的回答和专业的帮助。正如你们可能已经猜到的那样,我是一个相对新手的C++程序员。
不管怎样,我想知道Antoine的答案是否可以使用lambda表达式实现?
像这样:
std::set< …, [](){ my_comparator_code_here } > s;
????