The set::find is a built-in function in C++ STL which returns an iterator to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.
Syntax:
set_name.find(element)
Parameters: The function accepts one mandatory parameter element which specifies the element to be searched in the set container.
Return Value: The function returns an iterator which points to the element which is searched in the set container. If the element is not found, then the iterator points to the position just after the last element in the set.
Below program illustrates the above function.
CPP
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(1);
s.insert(4);
s.insert(2);
s.insert(5);
s.insert(3);
auto pos = s.find(3);
cout << "The set elements after 3 are: " ;
for ( auto it = pos; it != s.end(); it++)
cout << *it << " " ;
return 0;
}
|
OutputThe set elements after 3 are: 3 4 5
Time Complexity: The time complexity of set_name.find( key ) is O( log N ). As the elements are stored in a sorted manner by default.
Special Case: When the element being searched for is not present in the set, an iterator pointing to the end of the set is returned.
Below program illustrates this:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
set< int > s;
s.insert(1);
s.insert(4);
s.insert(2);
s.insert(5);
s.insert(3);
auto pos = s.find(6);
if (pos != s.end())
cout << "Element found at position : "
<< distance(s.begin(), pos) << endl;
else
cout << "Element not present in set" ;
return 0;
}
|
OutputElement not present in set
Time complexity: O(log n) // n is the number of elements in the set
Auxiliary space: O(n)