find

Syntax:

    #include <algorithm>
    iterator find( iterator start, iterator end, const TYPE& val );

The find() algorithm looks for an element matching val between start and end. If an element matching val is found, the return value is an iterator that points to that element. Otherwise, the return value is an iterator that points to end.

For example, the following code uses find to search a vector of integers for the number 3:

   int num_to_find = 3;
 
   vector<int> v1;
   for( int i = 0; i < 10; i++ ) {
     v1.push_back(i);
   }
 
   vector<int>::iterator result;
   result = find( v1.begin(), v1.end(), num_to_find );
 
   if( result == v1.end() ) {
     cout << "Did not find any element matching " << num_to_find << endl;
   }
 
   else {
     cout << "Found a matching element: " << *result << endl;
   }

In the next example, shown below, the find function is used on an array of integers. This example shows how the C++ STL algorithms can be used to manipulate arrays and pointers in the same manner that they manipulate containers and iterators:

   int nums[] = { 3, 1, 4, 1, 5, 9 };
 
   int num_to_find = 5;
   int start = 0;
   int end = 2;
   int* result = find( nums + start, nums + end, num_to_find );
 
   if( result == nums + end ) {
     cout << "Did not find any number matching " << num_to_find << endl;
   } else {
     cout << "Found a matching number: " << *result << endl;
   }

Related Topics: adjacent_find, find_end, find_first_of, find_if, mismatch, search