std::find() is a standard algorithm provided by the C++ Standard Template Library (STL). It is used to find the first occurrence of a given value in a specified range. The function works with containers that provide iterators, such as arrays, vectors, lists, and deques.
Example: Using std::find() with sort()
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {1, 3, 6, 2, 9};
// Sorting the vector
sort(v.begin(), v.end());
// Search for element 6
auto it = find(v.begin(), v.end(), 6);
// Print index
cout << distance(v.begin(), it);
return 0;
}
Output
2
Explanation:
- sort(v.begin(), v.end()) sorts the vector in ascending order.
- After sorting, the vector becomes: {1, 2, 3, 6, 9}.
- std::find() performs a linear search to locate the value 6.
- distance() calculates the index of the found element in the sorted vector.
- Even though the container is sorted, std::find() does not use binary search; it still scans elements one by one.
Syntax
The std::find() is a C++ STL function defined inside <algorithm> header file.
std::find(first, last, value);
Parameters:
- first: Iterator to the first element of range.
- last: Iterator to the theoretical element just after the last element of range.
- value: Value to be searched.
Return Value:
- If the value is found, it returns an iterator to its position; otherwise, it returns the end iterator.
The following examples demonstrate the use of find() function for different cases:
Example 1: Search for an Element in the Array
#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;
}
Output
2
Explanation: In this example, the std::find() function returns an iterator pointing to the value 6. The distance() function is then used to determine its index, which is 2.
Example 2: Try to Find an Element That Is Not Present
#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 present
if (it != v.end())
// Print index
cout << distance(v.begin(), it);
else
cout << "Not Present";
return 0;
}
Output
Not Present
Explanation: If the element is not found, std::find() returns the iterator to the end of the range. By comparing the returned iterator with v.end(), we can determine that the element is not present in the vector.