我正在尝试创建一个函数,如果一个元素在向量中,则返回 true/false,但我收到错误

I am trying to make a function with that returns true/false if an element is in the vector but I am getting an error?

本文关键字:一个 false true 返回 错误 如果 创建 函数 向量 元素      更新时间:2023-10-16

我正在尝试使用 STL 在 C++ 中实现一个函数,该函数接受一个对象和一个对象向量,如果向量包含对象,则返回 true,否则为 false。以下是函数的实现:

bool belongs(vertex V, std::vector<vertex> &array)
{
  std::vector<vertex>::iterator it;
  it = find(array.begin(), array.end(), V);
  if(it != array.end())
  {
    return true;
  }
  else
  {
    return false;
  }
}

但是,我收到此错误:

 invalid operands to binary expression ('vertex' and 'const vertex')
        if (*__first == __value_)

我能做什么?我对使用面向对象编程的STL编程有点陌生,所以等待您的帮助。

主要问题是没有为顶点类型定义operator==find需要顶点类型来确定 2 个vertex实例是否相同)。您可以按如下方式定义一个:

#include <iomanip>
#include <iostream>
#include <vector>
#include <algorithm>
struct vertex
{
    float a, b;
    bool operator==(const vertex& o) const // <-- This method is what find is looking for
    {
        return a == o.a && b == o.b;
    }
};
bool belongs(vertex V, const std::vector<vertex>& array)
{
    return find(array.begin(), array.end(), V) != array.end();
}
int main()
{
    std::vector<vertex> v = { { 1, 2 }, { 3, 4 } };
    std::cout << std::boolalpha << belongs({ 4, 5 }, v);
    return 0;
}

住在科里鲁

我还缩短了归属的实现,它更清楚地表明:

return x;

而不是:

if (x)
    return true;
else
    return false;
相关文章: