Last Updated : 19 May, 2025
C++ find() is a built-in function used to find the first occurrence of an element in the given range. It works with any container that supports iterators, such as arrays, vectors, lists, and more. In this article, we will learn about find() function in C++.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 6, 2, 9};
// Search an element 6
auto it = find(v.begin(), v.end(), 6);
// Print index
cout << distance(v.begin(), it);
return 0;
}
Syntax of find()
The std::find() is a C++ STL function defined inside <algorithm> header file.
C++
Parameters:
Return Value:
The following examples demonstrates the use of find() function for different cases:
Search for an Element in the Array C++
#include <bits/stdc++.h>
using namespace std;
int main() {
int arr[5] = {1, 3, 6, 2, 9};
// Search an element 6
auto it = find(arr, arr + 5, 6);
// Print index
cout << distance(arr, it);
return 0;
}
In the above program, the find() function returns an iterator pointing to the value 6, and we use the distance() function to print the position of the value 6, which is 2.
Try to Find Element Which Not Present C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {1, 3, 6, 2, 9};
// Search an element 22
auto it = find(v.begin(), v.end(), 22);
// Check if element is preset
if (it != v.end())
// Print index
cout << distance(v.begin(), it);
else
cout << "Not Present";
return 0;
}
Explanation: The find() function returns the iterator to the end of the range if the element is not found. So, we compared returned iterator to the v.end() to check if the element is present in the vector.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4