C++ examples for STL Algorithm:find_if
Search element in a sequence for a condition with algorithm find_if
#include <iostream> #include <algorithm> // algorithm definitions #include <vector> // vector class-template definition #include <iterator> using namespace std; bool greater10(int value); // predicate function prototype int main()/* w w w.j a va 2s . c o m*/ { const int SIZE = 10; int a[SIZE] = { 10, 2, 17, 5, 16, 8, 13, 11, 20, 7 }; vector< int > v(a, a + SIZE); // copy of a ostream_iterator< int > output(cout, " "); cout << "Vector v contains: "; copy(v.begin(), v.end(), output); // display output vector // locate first occurrence of value greater than 10 in v vector< int >::iterator location = find_if(v.begin(), v.end(), greater10); if (location != v.end()) // found value greater than 10 cout << "\n\nThe first value greater than 10 is " << *location << "\nfound at location " << (location - v.begin()); else // value greater than 10 not found cout << "\n\nNo values greater than 10 were found"; } // determine whether argument is greater than 10 bool greater10(int value) { return value > 10; } // end function greater10