自定义键出现c++映射插入错误
c++ map insertion error with custom key
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。并且涉及类型转换的操作与非成员重载的工作更加一致,因此将二进制运算符定义为friend
或class {}
块之外是一个好习惯。
map<>
根据严格弱排序对密钥进行排序。严格弱排序仅基于小于类型的比较。(点击链接获取完整定义。)
值得注意的是,如果!(a < b) && !(b < a)
和map<>
依赖于该属性,则严格弱排序认为对象a和b等价。
如果在创建映射时没有为map<>
提供比较函数,则其比较函数默认为std::less< Key >
,这将调用您的operator<
。这意味着它永远不会调用您的operator==
,但它会调用operator<
。只要你的类是LessThan Comparable,那么std::less< Key >
将服从严格弱序的性质。
相关文章:
- 为什么映射插入和 map.find() 的单次迭代比插入和 map.find() 的两次单独迭代慢得多
- 如何编写用于多映射插入和擦除功能的 API?
- C++,映射插入&&文件流读取导致麻烦
- 多映射插入键类型信息 std::make_pair vs std::p air 构造函数
- 将一个映射插入到同一多重映射的另一个映射中会导致 SEG 错误
- 将元素插入 c++ 映射 - 插入方法的差异
- 使用boost::关联属性映射插入boost::BIMAP..失败
- STL 无序映射 - 插入到向量中
- C++在映射插入期间保证移动
- Visual Studio C++-std::映射插入失败
- C++映射插入
- 标准::映射插入/擦除的并发问题
- 不明确的映射.插入boost
- 无序映射插入复制元素
- 无序映射插入()错误
- 自定义键出现c++映射插入错误
- c++多映射插入两个以上的值
- 使用配对类型的映射插入
- 调试映射插入
- STL映射插入复制构造函数