STL Find Algorithm


What is the STL? string vector list Iterators sort

The find algorithm is an operation (function) that can be applied to many STL containers. It searches a subrange of the elements in a container (or all the elements), looking for an element that is "equal to" a specified value; the equality operator (==) must be defined for the type of the container's elements. The find algorithm can be used in the following way:

#include <vector>  // vector class library
#include <list>	   // list class library
#include <algorithm>	   // STL algorithms class library
using namespace std;
...
list<int> nums;
list<int>::iterator nums_iter;

nums.push_back (3);
nums.push_back (7);
nums.push_front (10);

nums_iter = find(nums.begin(), nums.end(), 3); // Search the list.
if (nums_iter != nums.end())
{
    cout << "Number " << (*nums_iter) << " found." << endl; // 3
}
else
{
    cout << "Number not found." << endl;
}

// If we found the element, erase it from the list.
if (nums_iter != nums.end()) nums.erase(nums_iter);
// List now contains: 10 7 

The find algorithm searches the specified subrange of the container's elements and stops when it finds the first element equal to the specified value, as defined by the equality (==) operator as applied to the container's elements. If this operator is defined for a programmer-defined type (as is the case with the string class), then a search for the programmer-defined type can be done just as easily as for a built-in type.

Note that the search value (the third argument to the find function) must be of the same type as the elements stored in the container, or at least of a type that the compiler can automatically convert. In many cases, it will be necessary to create and initialize a temporary data object for this purpose.

The return value of the find function is an iterator specifying the position of the first matching element. If no matching element is found, the return value is equal to the iterator specifying the end of the element subrange (in the example above, the end of the list).


This document was written by Dr. Mark J. Sebern. (See stl) and last updated on December 13, 1998.