【问题标题】:Using vector std::find with a user-created object - third argument将向量 std::find 与用户创建的对象一起使用 - 第三个参数
【发布时间】:2015-08-06 07:41:01
【问题描述】:

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

如果需要进一步说明,请告诉我。

谢谢

【问题讨论】:

  • 查看您的错误消息,并问问自己std::find 应该如何知道它何时找到了您要查找的项目。
  • 如何比较它们?
  • 使用运算符 ==.
  • 我猜我需要超载...
  • @CollinOladimeji “我猜我需要超载...”宾果游戏!

标签: c++ stl iterator find


【解决方案1】:

您需要为您的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;
}

希望该代码可以更清楚地说明发生了什么。

【讨论】:

  • 谢谢。我的意思并不是听起来像一个完整的编程白痴,这是我大学工程学位的一部分,而我(还)不是最擅长的。
  • 我们都去过那里。一旦找到 std::find 的代码,就更容易理解了。搜索有关标准库的信息总是很有用的。
猜你喜欢
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多