C++ Standard Library C++ STL Library

C++ <algorithm> - find() Function



The C++ algorithm::find function returns an iterator to the first element in the range [first,last) that is equal to val. If no match is found, the function returns last.

Syntax

template <class InputIterator, class T>
   InputIterator find (InputIterator first, 
                       InputIterator last, 
                       const T& val);

Parameters

first Specify initial position of the input iterator. The range used is [first,last).
last Specify final position of the input iterator. The range used is [first,last).
val Specify the value to be searched in the range.

Return Value

Returns an iterator pointing to the first element in the range that is equal to val. If no match is found, the function returns last.

Time Complexity

Linear i.e, Θ(n).

Example:

In the example below, the algorithm::find function is used to find a given value in the given sequence.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main (){
  int arr[] = {10, 15, 12, 15, 14, 12};
  int * p;
  vector<int> vec = {10, 15, 12, 15, 14, 12};
  vector<int>::iterator it;

  //search for 15 in the array
  p = find(arr, arr+6, 15);

  //search for 20 in the vector
  it = find(vec.begin(), vec.end(), 20);

  //print result for array
  if(p != arr+6) {
    cout<<"Element found in the array: "<<*p<<"\n";
  }
  else {
    cout<<"Element is not found in the array.\n";
  }

  //print result for vector
  if(it != vec.end()) {
    cout<<"Element found in the vector: "<<*it<<"\n";
  }
  else {
    cout<<"Element is not found in the vector.\n";
  }

  return 0;
}

The output of the above code will be:

Element found in the array: 15
Element is not found in the vector.

❮ C++ <algorithm> Library