std :: map的自定义比较器不起作用

时间:2017-06-03 08:20:52

标签: c++ dictionary struct std stdmap

在编写一些C ++代码时,我遇到了以下现象:

我的地图看起来像这样:

std::map<test_struct_t*, unsigned int, cmp_by_value> testmap;

这个地图位于我的程序中全局,结构定义为:

struct test_struct_t {
  int x; int y; int val;

  bool operator<(const test_struct_t &o) const {
      return x < o.x || y < o.y || val < o.val;
  }
  test_struct_t(int a, int b, int c) : x(a), y(b), val(c) {}
};

我写的自定义比较器是:

struct cmp_by_value {
  bool operator()(const test_struct_t *a, const test_struct_t *b) const 
  {
      return *a < *b;
  }
};

现在,在我的主要方法中,我执行以下操作:

testmap.insert({new test_struct_t(0, 0, 2 ), 6});
testmap.insert({new test_struct_t(0, 1, 2 ), 6});
testmap.insert({new test_struct_t(1, 1, 0 ), 6});
testmap.insert({new test_struct_t(1, 2, 0 ), 6});
testmap.insert({new test_struct_t(2, 1, 0 ), 6});
testmap.insert({new test_struct_t(1, 2, 1 ), 6});
testmap.insert({new test_struct_t(1, 2, 0 ), 6});

然后我用一些格式方法打印地图中的值:

std::string format(test_struct_t *e) {
    std::stringstream ss;
    ss << "(" << e->x << "," << e->y << ") = " << e->val;
    return ss.str();
}

主要是:

std::map<test_struct_t*, unsigned int>::iterator it;
  for (it = testmap.begin(); it != testmap.end(); ++it) {
      std::cout << format(it->first) << std::endl;
 }

我的程序提供以下输出:

(1,1) = 0
(1,2) = 0
(1,2) = 1
(2,1) = 0
(1,2) = 0
(0,0) = 2
(0,1) = 2

有人可以向我解释为什么有重复的条目“(1,2)k = 0”?当我删除其中一个插入的语句时,一切都很好,没有重复。有什么想法吗?

编辑:我发现非常有趣的是:

testmap[new test_struct_t(0, 0, 2 )] = 6;
testmap[new test_struct_t(0, 1, 2 )] = 6;
testmap[new test_struct_t(1, 1, 0 )] = 6;
testmap[new test_struct_t(1, 2, 0 )] = 6;
testmap[new test_struct_t(2, 1, 0 )] = 6;
testmap[new test_struct_t(1, 2, 1 )] = 6;
testmap[new test_struct_t(1, 2, 0 )] = 6;

给出这个:

(0,0) = 2
(1,1) = 0
(1,2) = 0
(0,1) = 2

1 个答案:

答案 0 :(得分:4)

你的歌剧院&lt;没有定义严格的弱排序。尝试

bool operator<(const test_struct_t &o) const {
   return std::tie(x,y,val)<std::tie(o.x,o.y,o.val);
}
相关问题