How to Search an Element in Unordered_Set

Since the value of an element defines it, sets are a form of associative container in which each element must be special. The element’s value cannot be changed after it has been added to the set, but the element’s modified value can be removed and added again.

A hash table is used to implement an unordered set, with keys hashed into hash table indices to ensure that insertion is always random. All operations on the unordered set take constant time O(1) on average, which can go up to linear time O(n) in the worst case depending on the internally used hash function, but they perform very well in practise and generally provide a constant time lookup operation.



set ={ 5, 2, 3, 9, 8, 2, 3, 5, 8, 9 }   element =9


9 is present in the set

Given a unordered_set, the task is to search an element in it.

Find an Element in Unordered_Set

1)find() function in unordered_set

The unordered set::find() function is a C++ STL built-in function for searching for an element in a container. If the element is located, it returns an iterator to it; otherwise, it returns an iterator pointing to unordered set::end ().




The element to be searched for must be defined as a mandatory parameter key in this feature.


 If the element is located, it returns an iterator to it, otherwise it returns an iterator pointing to the end of unordered set.

2)Finding an element in unordered set

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
    // intializing unordered set by inializer list
    std::unordered_set<int> arrayset(
        { 5, 2, 3, 9, 8, 2, 3, 5, 8, 9 });
    // taking a iterator
    std::unordered_set<int>::const_iterator itr;
    // given element which should be searched
    int element = 9;
    // using find
    itr = arrayset.find(element);
    // if the iterator is not pointed to end then the element is
    // present in set
    if (itr != arrayset.end()) {
        cout << element << " is present in the set";
    else {
        cout << element << " is not present in the set";


9 is present in the set

Related Programs: