C++ 使用带有谓词的 std::find

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14437825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:20:18  来源:igfitidea点击:

using std::find with a predicate

c++vectorfindpredicate

提问by mahmood

I want to use std::findfunction along with a predicate (not sure if I use the correct word). Here is the code

我想将std::find函数与谓词一起使用(不确定我是否使用了正确的词)。这是代码

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class foo {
public:
  typedef pair< int, vector<int> > way;
  typedef pair< int, int > index;
  typedef pair< index, vector<way> > entry;
  vector< entry > table;

  void bar() 
  {
     vector<int> v1;
     v1.push_back(1);
     v1.push_back(2);

     way w = make_pair( 1, v1 );
     vector<way> v2;
     v2.push_back(w);

     index id = make_pair( 10, 20 );
     entry en = make_pair( id, v2 );
     table.push_back( en );
  }
  void insert()
  {
     index new_id = make_pair( 10, 20 );
     if ( find(table.begin(), table.end(), new_id) != table.end() ) {
        // index matched in the table
        // then I will push back a new pair (way)
        // to the second part of the entry
     }
  }
};
int main()
{
  foo f;
  f.bar();
  f.insert();
  return 0; 
}

As you can see, find()should search the tablebased on the first element in each entry. Right now, it says that ==is not overloaded to compare a pair.

如您所见,find()应该table根据每个条目中的第一个元素进行搜索。现在,它说==比较 a 没有过载pair

回答by Christian Rau

You want std::find_if:

你想要std::find_if

...
if(find_if(table.begin(), table.end(), [&new_id](const entry &arg) { 
                                           return arg.first == new_id; }) != ...)

EDIT:If you don't have C++11 (and therefore no lambdas), you have to create a custom functor (function or function object) to do the comparison of entry::firstwith the searched index:

编辑:如果您没有 C++11(因此没有 lambdas),您必须创建一个自定义函子(函数或函数对象)来entry::first与 searched进行比较index

struct index_equal : std::unary_function<entry,bool>
{
    index_equal(const index &idx) : idx_(idx) {}
    bool operator()(const entry &arg) const { return arg.first == idx_; }
    const index &idx_;
};

...
if(find_if(table.begin(), table.end(), index_equal(new_id)) != ...)

EDIT:Since an indexis just a pair of ints, you may also just capture it by value than const reference, to keep the code clearer and more concise, but it doesn't really matter either.

编辑:由于 anindex只是一对ints,您也可以只按值捕获它而不是 const 引用,以使代码更清晰和更简洁,但这也无关紧要。

回答by Daniel Laügt

In C++11, you can use also std::any_of

在 C++11 中,你也可以使用 std::any_of

if (std::any_of(table.cbegin(), table.cend(),
                [&new_id](const entry &arg) { return arg.first == new_id; }))