【问题标题】:Undefined reference to operator!= when using std::unordered_set使用 std::unordered_set 时对 operator!= 的未定义引用
【发布时间】:2018-04-14 18:42:46
【问题描述】:

我一直在使用一组模板函数contains

代码如下:

template<class V>
bool contains(const std::unordered_set<V>& c, const V& e)
{
    return c.find(e) != c.cend();
}

我也有 std::set、std::map 和 std::unordered_map 的类似版本

但是,我最近在使用它时遇到了链接错误:

CMakeFiles/dietAgent.dir/agent/workflow/autoscale/AutoscaleCoreScheduler
.cc.o : Dans la fonction « bool contains<WfNode*, WfNode*>
(std::unordered_set<WfNode*, std::hash<WfNode*>, std::equal_to<WfNode*>, 
std::allocator<WfNode*> > const&, WfNode* const&) » :
    /home/amxx/Work/Thesis/Code/diet/src/utils/stdext.hh:51 : référence 
indéfinie vers « std::integral_constant<bool, true> operator!=
<std::__detail::_Node_const_iterator<WfNode*, true, false>, 
std::__detail::_Node_const_iterator<WfNode*, true, false> >
(std::__detail::_Node_const_iterator<WfNode*, true, false> const&, 
std::__detail::_Node_const_iterator<WfNode*, true, false> const&) »

我从错误中了解到的是迭代器没有 operator!= ... WTF 吗?

更新:

显然,模板化包装器不应该受到责备。我尝试使用

if (mySet.find(value) != mySet.end()) { ... }

直接(而不是调用contains),我得到了相同的undefined referennce to operator!=

【问题讨论】:

  • @wally,我试过但没有成功...可能是因为问题出在链接上...
  • WfNode 对象是否随时间变化,或者它们是不可变的?如果地址是集合中的“值”,则可能无关紧要。
  • WfNode 不是 const,它们包含非常量方法,但指针不应该受到影响
  • cend 更改为end 将比较std::__detail::_Node_const_iteratorstd::__detail::_Node_iterator,这并不能解决任何问题并增加了不必要的差异

标签: c++ iterator std


【解决方案1】:

在您的类中,您需要重载运算符 !=

或者您可以使用运算符 ==,如下例所示:

template<class V>
bool contains(const std::unordered_set<V>& c, const V& e)
{
    return !(c.find(e) == c.cend());
}

【讨论】:

  • 我尝试过!( == ),但这并没有解决问题。我的容器也包含指向类的指针,所以我不需要在我的类中实现这些运算符,因为它们不需要比较指针。再一次,如果您查看错误,我得到无法比较的对象是 std::__detail::_Node_const_iterator&lt;WfNode*, true, false&gt;
猜你喜欢
  • 2021-04-20
  • 2021-04-13
  • 2011-04-13
  • 2015-03-29
  • 2013-07-03
  • 1970-01-01
  • 2021-07-19
相关资源
最近更新 更多