std find if

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

Effects

Finds the first element in a range for which the predicate function pred returns true.

Parameters

first => iterator pointing to the beginning of the range last => iterator pointing to the end of the range pred => predicate function(returns true or false)

Return

An iterator that points to the first element within the range the predicate function pred returns true for. The iterator points to last if no element satisfies pred

Example

The example uses std::ranges::find_if (C++20) and class template argument deduction (C++17).

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

/*
    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:
  explicit Greater(int than) : than_(than) {}

  bool operator()(int data) const 
  {
    return data > than_;
  }
};


int main()
{

  const std::vector myvec{2, 5, 6, 10, 56, 7, 48, 89, 850, 7, 456};
  
  //with a lambda function
  const auto gt10 = std::ranges::find_if(myvec, [](int value) {
    return value > 10;
  });
  
  //with a function pointer
  const auto pow10 = std::ranges::find_if(myvec, multOf10);

  //with functor
  const auto gt5 = std::ranges::find_if(myvec, Greater{5});

  //not Found
  const auto nf = std::ranges::find_if(myvec, Greater{1000});

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



std::cout << "First item >   10: " << *gt10 << '\n';
std::cout << "First Item n * 10: " << *pow10 << '\n';
std::cout << "First Item >    5: " << *gt5 << '\n';
}
item not found
First item >   10: 56
First Item n * 10: 10
First Item >    5: 6

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents