How to use the find() function in C++

The find() function in C++ helps to search for an element within the specified range. This function is available in the <algorithm.h> header file.

Parameters

The find() function accepts the following parameters.

  • first: This is an iterator that points to the first index of the array or vector where we want to perform the search operation.

  • last: This is an iterator that points to the last index of the array or vector to where we want to perform the search operation.

  • value: This is the value that we want to search within the range [first, last) in the given array or vector.

Return value

The find() function returns an iterator that points to the val in the specified range. If the value is not found, then it returns an iterator to the last of the array or vector.

Code

Let’s look at the code now.

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main () {
vector<int> vec = { 10, 20, 30, 40 };
auto it = find(vec.begin(), vec.end(), 30);
if (it != vec.end())
cout << "Element found: " << *it;
else
cout << "Element not found.";
return 0;
}

Explanation

  • In lines 1 to 3, we import the required header files.
  • In line 8, we define a vector that contains some integer elements.
  • In line 9, we call the find() function and pass the required arguments. Here, we are searching for the number 30.
  • In lines 11 and 12, we check if the iterator returned from the find() function does not point to the last of the vector, which means we found that element in the vector.
  • In lines 13 and 14, if the iterator returned from find() function points to the last of the vector, it means the element is not present in the vector.