C++ Standard Library C++ STL Library

C++ unordered_set - find() Function



The C++ unordered_set::find function is used to search the container for an element equivalent to the specified value and returns the iterator to it if found, else returns the iterator to unordered_set::end.

Syntax

const_iterator find (const key_type& k) const;
iterator find (const key_type& k);

Parameters

k Specify value to search for.

Return Value

An iterator to the element if k is found, or unordered_set::end if k is not found.

Time Complexity

Average case: Constant i.e, Θ(1).
Worst case: Linear i.e, Θ(n).

Example:

In the example below, the unordered_set::find function is used to find the specified element in uSet.

#include <iostream>
#include <unordered_set>
using namespace std;
 
int main (){
  unordered_set<int> uSet{55, 25, 128, 5, 72};
  unordered_set<int>::iterator it;

  it = uSet.find(25);
  uSet.erase(it);
  uSet.erase(uSet.find(5));

  cout<<"uSet contains: ";
  for(it = uSet.begin(); it != uSet.end(); ++it)
    cout<<*it<<" ";

  return 0;
}

The output of the above code will be:

uSet contains: 72 128 55 

❮ C++ <unordered_set> Library

5