使用带谓词的std :: find

mah*_*ood 11 c++ predicate vector find

我想使用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; 
}
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*ica 28

你想要std::find_if:

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

编辑:如果你没有C++ 11(因此没有lambdas),你必须创建一个自定义函子(函数或函数对象)来entry::first与搜索的比较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)) != ...)
Run Code Online (Sandbox Code Playgroud)

编辑:因为一个index只是一对ints,你也可能只是通过值捕获它而不是const引用,以保持代码更清晰,更简洁,但它也没关系.


Dan*_*ügt 5

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

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