自定义键出现c++映射插入错误

c++ map insertion error with custom key

本文关键字:映射 插入 错误 c++ 自定义      更新时间:2023-10-16

Hi我定义了如下所示的自定义键。当我创建std::map时,我的印象是map会引用我的键中定义的运算符==来检测两个键是否相同,但这不是真的。你能告诉我从这张地图上消除重复的正确逻辑吗?

class Key
{
public:
    Key(char * init, long l): equipNumber(l)
    {
            memcpy(initials, init, sizeof(initials));
    }
    bool operator==(const Key & other) const
    {
            bool result = true;
            cout << "Comparing: " << initials << " with " << other.initials;
            result &= (!memcmp(initials, other.initials, sizeof(initials)));
            cout << " And result is: " << result << endl;
            cout << "Comparing: " << equipNumber << " with " << other.equipNumber << endl;
            result &= (equipNumber == other.equipNumber);
            return result;
    }
    bool operator<(const Key & other) const
    {
            bool result = true;
            result &= (equipNumber < other.equipNumber);
            return result;
    }
private:
    char initials[5];
    long equipNumber;
};

map调用operator <(或给定的比较函子)两次以确定相等性:! (a < b) && ! (b < a)表示a == b。碰巧的是,该对的第一个小于运算已经作为递归下降的一部分执行,因此没有太多(或任何)额外成本。它极大地简化了定制。

顺便说一下,

        bool result = true;
        result &= (equipNumber < other.equipNumber);
        return result;

可能只是CCD_ 5。并且涉及类型转换的操作与非成员重载的工作更加一致,因此将二进制运算符定义为friendclass {}块之外是一个好习惯。

map<>根据严格弱排序对密钥进行排序。严格弱排序仅基于小于类型的比较。(点击链接获取完整定义。)

值得注意的是,如果!(a < b) && !(b < a)map<>依赖于该属性,则严格弱排序认为对象a和b等价

如果在创建映射时没有为map<>提供比较函数,则其比较函数默认为std::less< Key >,这将调用您的operator<。这意味着它永远不会调用您的operator==,但它会调用operator<。只要你的类是LessThan Comparable,那么std::less< Key >将服从严格弱序的性质。