std::find is a function defined inside <algorithm> header file that finds the element in the given range. It returns an iterator to the first occurrence of the specified element in the given sequence. If the element is not found, an iterator to the end is returned.
Syntax:
input_iterator std::find(input_iterator first, input_iterator last, const T& value);
Parameters:
- first: iterator to the initial position in the sequence.
- last: iterator to position just after the final position in the sequence. (Note that vector.end() points to the next position to the last element of the sequence and not to the last position of the sequence).
- value: value to be searched.
Return Value :
- If the value is found in the sequence, the iterator to its position is returned.
- If the value is not found, the iterator to the last position is returned.
NOTE: input_iterator is the iterator type of the used container and T is the typename defined in the function template.
Example:
C++
#include <bits/stdc++.h>
int main()
{
std::vector< int > vec{10, 20, 30, 40};
std::vector< int >::iterator it;
std::cout << "Original vector :" ;
for ( int i = 0; i < vec.size(); i++)
std::cout << " " << vec[i];
std::cout << "\n" ;
int ser = 30;
it = std::find(vec.begin(),
vec.end(), ser);
if (it != vec.end())
{
std::cout << "Element " << ser <<
" found at position : " ;
std::cout << it - vec.begin() <<
" (counting from zero) \n" ;
}
else
std::cout << "Element not found.\n\n" ;
return 0;
}
|
Output
Original vector : 10 20 30 40
Element 30 found at position : 2 (counting from zero)
Time Complexity: O(n)
Auxiliary Space: O(1)
NOTE: std::find() function is defined inside <algorithm> header file. So, we need to include that header file before using find function.
As we can see that the time complexity of the std::find() is O(n) and it also works on unsorted sequences, we can conclude that it uses the linear search algorithm in its implementation.
Related Articles:
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Sep, 2023
Like Article
Save Article