c++ - std::map具有非唯一的键顺序但唯一的比较

标签 c++ stl key strict-weak-ordering

考虑以下代码:

#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。这似乎是由于attr1中仅比较了operator<所致。但是,如果我是对的,则比较不必是强排序,而是弱排序就足够了。这里还有其他错误吗?还是我必须为它定义一个operator<

Key1 !< Key2 && Key2 !< Key1 implies that Key1 == Key2


正确吗?

最佳答案

比较元素时,std::map完全不使用operartor ==。默认情况下,在这种情况下,它使用std::less,后者使用您的operator <。由于您的operator <仅比较attr1,并且两个对象都具有相同的attr1,因此这两个对象被认为是等效的,因此在 map 中您只有一个对象。
要解决此问题,您需要检查两个成员,并且可以使用 std::tie 技巧来创建一个元组,以便您喜欢

bool operator< (const Key& s1, const Key& s2){
    return std::tie(s1.attr1, s1.attr2) < std::tie(s2.attr1, s2.attr2);
}

另一种选择是使用std::unordered_map,它使用哈希算法和相等运算符。使用它,您可以仅对attr1进行哈希处理,但是让相等运算符同时检查attr1attr2以确保未添加真正的重复项。

关于c++ - std::map具有非唯一的键顺序但唯一的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63887687/

相关文章:

java - 为 Guava Cache 选择键

c++ - boost:如何使当前线程休眠直到给定 ptime?

c++ - QtSerialPort 在错误的线程中实例化,导致信号/插槽失败

c++ - 使用 CMake 安装时永久存储环境变量

c++ - 放弃 auto_ptr 包含对象的所有权

javascript - 在 JavaScript 中实现 Google map API key

c++ - 使用递归的红黑树高度

c++ - 为了性能,我应该更喜欢数组而不是 vector 吗?

c++ - 如何按其 .second 参数对 map 进行排序

sql-server - 如何在 SQL Server 中编写索引、键、外键脚本