【问题标题】:Using the find_if() function使用 find_if() 函数
【发布时间】:2014-05-23 16:13:04
【问题描述】:

我有一个结构向量说“v”。我需要找到 ID 与给定 ID 匹配的“v”的某个项目。

我在另一篇文章中发现要走的路是“find_if”。所以我实现了以下内容:

std::find_if(v.begin(), v.end(), MatchesID(id))!= v.end();

注意:我已经按照帖子中的建议正确创建了 MatchesID 类。

现在,我如何访问包含我搜索的“id”的特定矢量项?

我试过了:

std::vector<int>::iterator it = std::find_if (v.begin(), v.end(), MatchesID(id));

但它给出了错误。

编辑:错误 C2440:“正在初始化”:无法从“std::_Vector_iterator<_ty>”转换为“std::_Vector_iterator<_ty>”

EDIT2:为了完整起见,我也是基于帖子:Search for a struct item in a vector by member data

【问题讨论】:

  • 它给出了哪些错误?
  • 你试过std::vector&lt;int&gt;::const_iterator吗?此外,另一种选择是使用 auto 并让编译器为您找出类型。
  • 请显示MatchesID的定义
  • 如果它是一个结构体向量,似乎迭代器类型应该是vector::iterator。或者,如果您的编译器支持 C++11,您可以只写“auto it = ...”
  • 您应该准确指定v 的类型。为了最大限度地提高效率,您实际上应该提供一个重现问题的完整示例。

标签: c++ vector std


【解决方案1】:

你说你的向量有structs 类型为mystruct(即你有一个std::vector&lt;mystruct&gt;)。然而,您正在分配一个迭代器std::vector&lt;mystruct&gt;::iterator,而std::find_if 将返回一个std::vector&lt;int&gt;::iterator 类型的迭代器。解决方案:

std::vector<mystruct>::iterator it = std::find_if (v.begin(), v.end(), MatchesID(id));

auto it = std::find_if (v.begin(), v.end(), MatchesID(id));

【讨论】:

    【解决方案2】:

    我认为问题已降格为“我如何使这项工作”

    auto there= std::find_if(v.begin(), v.end(), MatchesID(id))!= v.end();

    答案是

    #include <vector>
    #include <algorithm>
    
    struct MatchesID
    {
        int id;
        MatchesID(int id): id(id){}
        bool operator()(int id){ return this-> id== id; }
    };
    
    int main()
    {
        std::vector<int> v;
        std::vector<int>::iterator i= std::find_if(v.begin(), v.end(), MatchesID(42));
    }
    

    您可以将其与您的版本进行比较以找出错误。

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      相关资源
      最近更新 更多