使用 std::map 时,我应该为键类型重载 operator== 吗? [英] When using std::map should I overload operator== for the key type?

查看:35
本文介绍了使用 std::map 时,我应该为键类型重载 operator== 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::map 不应该有重复的键,所以当我有一个自定义类型时它怎么知道我有一个重复的键,我需要重载重载运算符==吗?还是会隐式创建?

The std::map should not have duplicated keys so how does it knows I have a duplicated key when I have a custom type, do I need do overload overload operator==? Or it will be implicitly created?

根据文档,我只需要操作员<但这还不足以保持密钥的唯一性.

According to the documentation I only need the operator< but this is not enough to maintain the keys' unicity.

考虑这个例子:

class MyType{
public:
  MyType(int newId){
    id = new int;
    *id = newId;
  };
  ~MyType{
    delete id;
  }
private:
  int* id;
};

int main(){
  std::map<MyType,int> myMap;

  std::pair<std::map<MyType,int>::iterator,bool> ret;
  ret = myMap.insert ( std::pair<MyType,int>(myType(2),100) );

  if (!ret.second) {//now how can he knows that?
    std::cout << "element already existed" << endl;
  }
}

推荐答案

std::map 不关心键的字面唯一性.它关心键等价.键 ab 根据定义是等效的,当 a <;bb 为真.

std::map does not care about literal unicity of the keys. It cares about keys equivalence. The keys a and b are equivalent by definition when neither a < b nor b < a is true.

还要注意 std::map 不直接使用 operator <.std::mapoperator < 一无所知.取而代之的是std::map 使用比较谓词,其类型被指定为std::map 模板的第三个参数.该参数的默认值为 std::less.std::less 的实现将比较委托给 operator < (除非专门化不同).这就是 operator < 发挥作用的方式.但是你总是可以提供你自己的谓词,它不一定使用operator <.

Note also that std::map does not directly use operator <. std::map does not know anything about operator <. Instead std::map uses the comparison predicate, whose type is specified as the third parameter of std::map template. The default value of that parameter is std::less. Implementation of std::less delegates the comparison to operator < (unless specialized differently). This is how operator < comes into play. But you can always supply your own predicate which will not necessarily use operator <.

但无论如何,这里的关键时刻是 std::map 使用排序较少"比较并且仅使用较少"比较.它不需要也不关心任何平等"比较.

But in any case the key moment here is that std::map uses an ordering "less" comparison and only "less" comparison. It does not need and does not care about any "equality" comparisons.

与此同时,std::unordered_map 将是另一回事.它依赖于谓词指定的无序相等"比较.默认情况下它是 std::equal_to.std::equal_to 的实现将调用委托给 operator ==(除非专门不同).

Meanwhile, std::unordered_map would be a different story. It relies on non-ordering "equality" comparison specified by a predicate. By default it is std::equal_to. Implementation of std::equal_to delegates the call to operator == (unless specialized differently).

这篇关于使用 std::map 时,我应该为键类型重载 operator== 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆