【问题标题】:map.find() returns seemingly randomly map.end()map.find() 看似随机地返回 map.end()
【发布时间】:2020-09-19 14:19:57
【问题描述】:

我在 C++ map 中使用自定义比较器。不幸的是,map.find() 经常在地图中找不到所需的条目。 重现这一点的代码非常简单:

#include <array>
#include <iostream>
#include <map>

using namespace std;

typedef struct DATA_t {
  array<int, 4> data;
} DATA_t;

struct DATA_cmp {
  bool operator()(const DATA_t& a, const DATA_t& b) const {
    for (int i = 0; i < a.data.size(); ++i)
      if (a.data[i] < b.data[i]) return true;
    return false;
  }
};

int main(int argc, char** argv) {
  map<DATA_t, int, DATA_cmp> index;
  DATA_t data1 = {1, 2, 4, 8};
  DATA_t data2 = {1, 3, 5, 7};
  DATA_t data3 = {0, 6, 7, 8};
  DATA_t data4 = {0, 1, 1, 2};
  index[data1] = 1;
  index[data2] = 2;
  index[data3] = 3;
  index[data4] = 4;
  cout << "data1 " << (index.find(data1) == index.end() ? "not found" : "found") << endl;
  cout << "data2 " << (index.find(data2) == index.end() ? "not found" : "found") << endl;
  cout << "data3 " << (index.find(data3) == index.end() ? "not found" : "found") << endl;
  cout << "data4 " << (index.find(data4) == index.end() ? "not found" : "found") << endl;
  return 0;
}

输出应该是“找到”的所有行,但我得到:

data1 found
data2 not found
data3 found
data4 found

我怀疑问题是我的比较函数,但我没有看到我的错误。

【问题讨论】:

  • 顺便说一句,在 c++ 中,typedef struct S {} S; --> struct S {};,正如我在答案中的演示中所展示的那样。

标签: c++ find comparator stdmap


【解决方案1】:

您的比较函数不正确。考虑以下键会发生什么:

{ 1, 2, 3, 4 }  // #1
{ 1, 3, 2, 4 }  // #2

现在比较#1#2 将返回true,因为第二个索引更小(2 #2 和#1 也会返回true,因为第三个索引更小(2

这违反了键具有严格弱排序的要求,即a &lt; bb &lt; a 不能同时为真。

您可以通过在这样的数组上使用 operator&lt; 来解决此问题:

struct DATA_cmp {
  bool operator()(const DATA_t& a, const DATA_t& b) const {
    return a.data < b.data;
  }
};

这是demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2014-11-16
    • 2014-12-10
    • 1970-01-01
    相关资源
    最近更新 更多