【问题标题】: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?如果元素在向量中,我正在尝试创建一个返回 true/false 的函数,但出现错误?
【发布时间】:2016-05-21 23:39:37
【问题描述】:

我正在尝试使用 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 编程有点陌生,所以期待您的帮助。

【问题讨论】:

    标签: oop c++ algorithm data-structures stl


    【解决方案1】:

    主要问题是没有为顶点类型定义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;
    }
    

    Live on Coliru

    我还缩短了 belongs 的实现,它更清晰:

    return x;
    

    而不是:

    if (x)
        return true;
    else
        return false;
    

    【讨论】:

    • 我做了一个顶点类,那我该怎么办?
    • @DanishAmjadAlvi 为它实现 operator==,我没有你的顶点类,所以我做了一个。
    猜你喜欢
    • 2021-04-30
    • 2019-10-30
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2014-07-26
    • 1970-01-01
    • 2018-03-23
    相关资源
    最近更新 更多