using std::find with a predicate

梦想与她 提交于 2020-01-02 00:58:06

问题


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

#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 table based on the first element in each entry. Right now, it says that == is not overloaded to compare a pair.


回答1:


You want 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::first with the 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 index is 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.




回答2:


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

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


来源:https://stackoverflow.com/questions/14437825/using-stdfind-with-a-predicate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!