【问题标题】:Searching const key type in set causes compile error在集合中搜索 const 键类型会导致编译错误
【发布时间】:2016-11-02 08:29:08
【问题描述】:

我有一个指针类型的set,但使用 const 指针搜索是不可能的,我的代码如下:

#include <set>
#include <string>

using namespace std;

struct Node
{
  string name;
  int id;

  Node(const string &name, int id):
    name(name),
    id(id)
  {}
};

struct Comprator
{
  bool operator()(const Node* lhs, const Node* rhs) const
  {
    return lhs->id < rhs->id;
  }
};

int
main(int argc, char *argv[])
{
  set<Node*, Comprator> d;

  Node* node3 = new Node("foo", 4);

  d.insert(node3);

  const Node* node4 = node3;

  auto it = d.find(node4);

  return 0;
}

我收到以下错误:

main.cc: In function ‘int main(int, char**)’:
main.cc:38:25: error: invalid conversion from ‘const Node*’ to ‘std::set<Node*, Comprator>::key_type {aka Node*}’ [-fpermissive]
   auto it = d.find(node4);
                         ^
In file included from /usr/include/c++/5/set:61:0,
                 from main.cc:2:
/usr/include/c++/5/bits/stl_set.h:694:7: note:   initializing argument 1 of ‘std::set<_Key, _Compare, _Alloc>::iterator std::set<_Key, _Compare, _Alloc>::find(const key_type&) [with _Key = Node*; _Compare = Comprator; _Alloc = std::allocator<Node*>; std::set<_Key, _Compare, _Alloc>::iterator = std::_Rb_tree_const_iterator<Node*>; std::set<_Key, _Compare, _Alloc>::key_type = Node*]’
       find(const key_type& __x)

如果我将 Node* 更改为 int 一切正常,我不明白问题所在。我使用 c++11 和 g++-5.4.0。

编辑:

正如@Piotr Skotnicki 在 c++14 的 cmets 中解释的那样,下面的比较器代码可以编译:

struct Comprator
{
  using is_transparent = void;

  bool operator()(const Node* lhs, const Node* rhs) const
  {
    return lhs->id < rhs->id;
  }
};

【问题讨论】:

  • 您可以在Comprator的声明中添加using is_transparent = void;
  • 我将语句添加到我的比较器类中,但没有任何改变。
  • 您需要使用-std=c++14 模式标志
  • 是的,它有效,感谢您的帮助。如果有的话,请给我一个链接,以找出这在 c++14 中有效的原因。

标签: c++ c++11 set g++ c++14


【解决方案1】:

const Node*(指向 const Node 的非 const 指针)不是 const 键 - 那将是 Node* const(指向 Node 的 const 指针)。

要么将您的 set 更改为一组 Node const*,要么将指向非 const Nodes 的指针传递给它。

这里有更深入的解释:link

【讨论】:

  • 是的,这是真的,我忘记了const Node*Node* const之间的区别
  • 您认为在这里使用const_cast 合适吗?因为总的来说我认为const_cast 是一个恶魔,但另一方面它必须可以使用指针的 const 来从集合中查询。
  • @MohsenTamiz 这将是安全的,因为您不会在 find 操作期间访问该元素。但这闻起来像一个设计问题,你是对的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 2011-03-09
  • 1970-01-01
  • 2018-05-16
  • 2017-01-19
  • 1970-01-01
相关资源
最近更新 更多