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

时间:2015-05-24 20:20:49

标签: c++ stl iterator find

我正在尝试使用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')|

如果需要进一步澄清,请告诉我。

由于

1 个答案:

答案 0 :(得分:3)

You need to overload the == operator for your Vertex class so std::find understands when one vertex is the same as another. This is what Benjamin was trying to walk you to.

The code for std::find can be found at 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;
}

Hopefully that code makes it more clear as to what is going on.