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.
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.
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.
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;elsecout << "Element not found.";return 0;}
find()
function and pass the required arguments. Here, we are searching for the number 30.find()
function does not point to the last of the vector, which means we found that element in the vector.find()
function points to the last of the vector, it means the element is not present in the vector.