查找与存储在向量中的对象相对应的迭代器

Finding an iterator corresponding to an object stored in a vector

本文关键字:对象 相对 迭代器 存储 向量 查找      更新时间:2023-10-16

我有一个向量v,其中包含a类型结构的对象。现在我需要找到存储在这个向量中的特定对象的迭代器。例如:

  struct a
    {
    };
    vector<a> v;
    struct temp;  //initialized

现在,如果我将使用

find(v.begin(),v.end(), temp);

则编译器生成表示运算符CCD_ 1不匹配的错误。

有什么解决方法可以让迭代器与向量中的对象相对应?

您必须为类提供bool operator==(const a& lhs, const a& rhs)相等运算符,或者将比较函子传递给std::find_if:

struct FindHelper
{
  FindHelper(const a& elem) : elem_(elem) {}
  bool operator()(const a& obj) const
  {
  // implement equality logic here using elem_ and obj
  }
  const a& elem_;
};
vector<a> v;
a temp;
auto it = std::find_if(v.begin(), v.end(), FindHelper(temp));

或者,在c++11中,您可以使用lambda函数而不是函子。

auto it = std::find_if(v.begin(), v.end(),  
                       [&temp](const a& elem) { /* implement logic here */ });