The C++ Standard Library consists of the header, <algorithm>
which defines a collection of functions (principally designed to deal with a range of elements). find()
is a method in the STL that returns an iterator pointing to the first element in the range which in equal to a certain value. If no element is found, the method returns the last iterator.
Syntax:
find( iterator_begin, iterator_end, val );
Parameters: The find()
method accepts 3 parameters
- iterator_begin: Iterator to the initial position
- iterator_end: Iterator to the final position ( Note: the range is [iterator_begin,iterator_end) )
- val: Value to match
Return value: Iterator pointing to the first element in the range which is equal to val. iterator_end if val not found
Example of find() method
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(3); v.push_back(5); v.push_back(3); vector<int>::iterator it = find(v.begin(), v.end(), 4); cout<<"Index of the element 4 is: "<< distance(v.begin(), it) << endl; }
Output:
Index of the element 4 is: 3