unordered_set find() function in C++

In this tutorial, we will learn how to use unordered_set find() function in C++. Before directly moving to the unordered_set find() in C++. Let’s understand first unordered_set in detail.

Unordered sets are containers that store unique elements in no distinct order.

Ref: http://www.cplusplus.com/reference/unordered_set/unordered_set/

Now let’s understand unordered_set find() in detail.

unordered_set find() in C++

The unordered_set::find() is a built-in standard library function in C++. It is used to search an element in the container. It returns an iterator to the element if found otherwise, it returns an iterator that refers to the unordered_set::find().

Syntax :

unordered_set_name.find(key);

The key specifies the element whose position is to find out.

The unordered_set find() function returns :

An iterator to the element is returned only if it is found. If it is not found it returns an iterator to the unordered_set::find().

//ilustraing the use of unordered_set in C++
#include <iostream> 
#include <string> 
#include <unordered_set> 
  
using namespace std; 
  
int main() 
{ 
  
   unordered_set<string> test = { "code", "speedy", "happy","learning" };  //defining the keys
  
    // use of find() function 
    if (test.find("speedy") != test.end()) { 
        cout << "found" << endl; 
    } 
    else { 
        cout << "not found" << endl; 
    } 
    if (test.find("enjoy") != test.end()) { 
        cout << "found" << endl; 
    } 
    else { 
        cout << "not found" << endl; 
    } 
  
    return 0; 
}

The above program displays the following output as :

found
not found

The program displays two outputs. Where first it checks the key speedy in the unordered set. Which is there in the unordered set hence, it displays found as the result of the execution. In the second if loop it checks the key enjoy from the unordered set. Which is not there in the unordered set hence, it displays not found as the result of the execution of the program.

Recommended tutorials: 

How to remove a particular character from a string in C++

C++ program to find the triplets with a given sum in an array

Leave a Reply

Your email address will not be published. Required fields are marked *