使用vector std::find和用户创建的对象(第三个参数)

Using vector std::find with a user-created object - third argument

本文关键字:参数 对象 三个 std vector find 创建 用户 使用      更新时间:2023-10-16

我试图利用std::find来搜索向量并返回找到所需对象的迭代器。我遇到的问题是,我不确定把什么作为第三个参数。下面是相关的代码行以及我正在使用的对象的定义。

功能:

vector<Vertex>::const_iterator findV = find(testV.begin(), testV.end(), vtx); 
//vtx is of type Vertex
类定义

:

class Vertex
{
    private:
        int currentIndex;
        double xPoint, yPoint, zPoint;
        vector<double> vertexAttributes;
    public:
        Vertex();
        ~Vertex();
        friend istream& operator>>(istream&, Vertex &);
        friend ostream& operator<<(ostream&, const Vertex &);
        double getIndex(){return currentIndex;}
        double get_xPoint(){return xPoint;}
        double get_yPoint(){return yPoint;}
        double get_zPoint(){return zPoint;}
};

从逻辑上讲,由于我正在搜索类型为Vertex的对象,因此第三个参数也应该是该类型,但这不起作用。

收到的错误是:

error: no match for 'operator==' (operand types are 'Vertex' and 'const Vertex')|

如果需要进一步澄清,请让我知道。

谢谢

您需要为Vertex类重载==操作符,以便std::find理解何时一个顶点与另一个顶点相同。这就是本杰明想带你去的地方。

std::find的代码可以在http://www.cplusplus.com/reference/algorithm/find/

找到
template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;
}