【问题标题】:std::map custom key non-uniqueness problemstd::map 自定义键非唯一性问题
【发布时间】:2010-11-29 20:26:11
【问题描述】:

在 Google 上找不到答案..

当我使用 std::string 时,以下工作正常。

map <fxString, int> test;
test.insert(pair <fxString, int> ("Bla", 1));
test.insert(pair <fxString, int> ("Bla", 2));
test.insert(pair <fxString, int> ("Bla", 3));
cout << fxInt2String(test["Bla"]) << endl;

应该输出1,却输出0

当我遍历映射时,每个键值对都在那里,彼此挨着嘲笑我。

fxString 定义了以下运算符: 运营商 > 运算符

还有更多,我对它们进行了测试..

格罗姆。

【问题讨论】:

  • 什么是fxStringfxInt2String
  • 您的&lt; 操作员是什么样的?
  • operator&lt; 应该为相等的对象返回 false。

标签: c++ stl map key


【解决方案1】:

“当我遍历地图时每个 键值对就在那里”

那么,您的fxString::operator&lt; 有问题,因为如果密钥已经存在,insert 成员函数应该无效。你确定这个操作符是 strict weak ordering 的模型吗?

假设操作符坏了,test["Bla"] 具有在地图中添加另一个元素的效果,默认值为 0。

【讨论】:

  • +1 - operator&lt; 几乎肯定是这两个问题的原因。地图插入每条新记录的原因是它搜索“Bla”,但找不到它。同样在检索中,它找不到'Bla',并返回一个默认值(同时添加一个新的对。)
  • @Eclipse:对,答案已编辑以解释为什么显示 0
  • 我对 operator
【解决方案2】:

这很好用(正如你所指出的)

map <string, int> test;
test.insert(pair <string, int> ("Bla", 1));
test.insert(pair <string, int> ("Bla", 2));
test.insert(pair <string, int> ("Bla", 3));
cout << test["Bla"] << endl;

因此,您的fxInt2String 函数或运算符重载肯定有问题。

要获得进一步的帮助,您应该向我们提供相关功能的代码。

【讨论】:

  • 我当然读过了。我刚刚提供了一个有效的示例(作者也知道这一点)。所以答案本身就是“所以你的 fxInt2String 函数或者你的操作符重载一定有问题。”如果没有更多代码,我们无能为力。
  • 为了您的满意而编辑:P
猜你喜欢
  • 2021-01-01
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2012-01-10
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多