【问题标题】:C++ finding class in vector using std::find raises errorsC++ 使用 std::find 在向量中查找类会引发错误
【发布时间】:2020-09-21 11:25:47
【问题描述】:

我正在尝试使用在 std::vector 中查找 SnekNode 对象

    auto it = std::find(snek_node_container.begin(), snek_node_container.end(), snek_node);

但它会引发编译器错误:

错误 C2676 二进制“==”:“SnekNode”未定义此运算符或 转换为预定义运算符可接受的类型

它指向 xutility 文件作为源,这不是很有帮助。当我尝试在类中定义一个 == 函数时,例如:

        SnekNode operator== (const SnekNode& rhs) {
        return (*this == rhs);
    }

我得到另一个编译错误:

“SnekNode”类型的 C2451 条件表达式是非法的

这也指向了 xutility 文件,遗憾的是它对我没有帮助。我在这里做错了什么?提前致谢!

【问题讨论】:

  • operator== 应该返回 bool 或可转换为 bool 的东西。
  • 错误字面意思是你的代码出了什么问题
  • 此外,您的运算符定义会创建无限递归。您需要自己实际比较每个成员(或使用 C++20 和 =default
  • A) operator == 通常应该返回 bool,B) 正如你所定义的那样,该运算符是无限递归的,因为它会调用自己......这应该如何工作?

标签: c++ class vector


【解决方案1】:

operator== 应该返回 bool。

此外,您需要单独比较成员。在您的代码中,您只需再次调用operator==,从而导致无限递归。

你可以做的是使用operator!=中的operator==来节省输入,例如:

struct SnekNode
{
    bool operator== (const SnekNode& rhs) const {
        return a == rhs.a &&
            b == rhs.b && 
            c == rhs.c;
    }

    bool operator!= (const SnekNode& rhs) const {
        return !(*this == rhs);
    }

    // auto operator<=>(const SnekNode&) const = default; // C++20

    int a{0};
    int b{1};
    int c{2};
};

在 C++20 中,您可以使用 default comparisons(宇宙飞船运算符)。

Live demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    相关资源
    最近更新 更多