【发布时间】:2021-01-01 09:00:12
【问题描述】:
考虑以下代码:
#include <iostream>
#include <map>
#include <utility>
struct Key{
int attr1, attr2;
Key(int attr1, int attr2) : attr1(attr1), attr2(attr2) {}
friend bool operator== (const Key& s1, const Key& s2);
friend bool operator< (const Key& s1, const Key& s2);
};
bool operator== (const Key& s1, const Key& s2){
return ((s1.attr1 == s2.attr1) && (s1.attr2 == s2.attr2));
}
bool operator< (const Key& s1, const Key& s2){
return (s1.attr1 < s2.attr1);
}
int main(void){
std::map<Key, int> mmap;
mmap.insert(std::make_pair(Key(10, 10), 5));
mmap.insert(std::make_pair(Key(10, 20), 5));
std::cout << mmap.size() << std::endl;
}
输出是1,我希望它是2。这似乎是因为在operator< 中只比较了attr1。但是,如果我是正确的,则比较不必是强排序,而是弱排序就足够了。这里是否还有其他错误,或者我必须为其定义一个operator<
Key1 !< Key2 && Key2 !< Key1暗示Key1 == Key2
是真的吗?
【问题讨论】:
标签: c++ stl key strict-weak-ordering