stdfind if

template <class InputIterator, class UnaryPredicate>
InputIterator find_if (InputIterator first, InputIterator last, UnaryPredicate pred);

效果

查找谓词函数 pred 返回 true 的范围中的第一个元素。

参数

first =>指向范围开头的迭代器 last =>指向范围结束的迭代器 pred =>谓词函数(返回 true 或 false)

返回

迭代器指向谓词函数 pred 返回 true 的范围内的第一个元素。如果未找到 val,则迭代器指向最后

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

/*
    define some functions to use as predicates
*/

//Returns true if x is multiple of 10
bool multOf10(int x) {
  return x % 10 == 0;
}

//returns true if item greater than passed in parameter
class Greater {
  int _than;

public:
  Greater(int th):_than(th){
    
  }
  bool operator()(int data) const 
  {
    return data > _than;
  }
};

int main()
{

  vector<int> myvec {2, 5, 6, 10, 56, 7, 48, 89, 850, 7, 456};
  
  //with a lambda function
  vector<int>::iterator gt10 = find_if(myvec.begin(), myvec.end(), [](int x){return x>10;}); // >= C++11
  
  //with a function pointer
  vector<int>::iterator pow10 = find_if(myvec.begin(), myvec.end(), multOf10);

  //with functor
  vector<int>::iterator gt5 = find_if(myvec.begin(), myvec.end(), Greater(5));

  //not Found
  vector<int>::iterator nf = find_if(myvec.begin(), myvec.end(), Greater(1000)); // nf points to myvec.end()

  //check if pointer points to myvec.end()
  if(nf != myvec.end()) {
    cout << "nf points to: " << *nf << endl;
  }
  else {
    cout << "item not found" << endl;
  }

  
  
  cout << "First item >   10: " << *gt10  << endl;
  cout << "First Item n * 10: " << *pow10 << endl;
  cout << "First Item >    5: " << *gt5   << endl;
  
  return 0;
}

输出

item not found
First item >   10: 56
First Item n * 10: 10
First Item >    5: 6