Std::map的自定义比较器不起作用 [英] Custom comparator for std::map not working

查看:66
本文介绍了Std::map的自定义比较器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写一些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;
  }
};

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

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

推荐答案

您的operator<没有定义严格的弱排序。尝试

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

这篇关于Std::map的自定义比较器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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