【问题标题】:Finding an iterator corresponding to an object stored in a vector查找与存储在向量中的对象对应的迭代器
【发布时间】:2013-02-25 04:23:19
【问题描述】:

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

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

现在如果我会使用

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

然后编译器生成错误,指出运算符 '==' 不匹配。

获取与向量中的对象对应的迭代器的任何解决方法?

【问题讨论】:

    标签: c++ stl


    【解决方案1】:

    您必须为您的类提供一个bool operator==(const a&amp; lhs, const a&amp; 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 */ });
    

    【讨论】:

    • 但是在 find_if 中我将如何传递要搜索的对象?
    • @SegmentationFault 您可以使用仿函数(我编辑了答案以显示示例)或在 C++11 中使用 lambda。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 2019-11-19
    • 2021-11-14
    • 2011-04-18
    相关资源
    最近更新 更多