How to Search an element in unordered_set

In this article we will see how to search if an element is present in an unordered_set or not.

std::unordered_set provides a member function find () that accepts an element of same type as set and search for that element in set.

If element is found then it returns the iterator pointing to that element else it returns an iterator pointing to end of set i.e. unordered_set::endl().

Let’s see an example,

#include <iostream>
#include <unordered_set>
#include <algorithm>

int main() {

	// Create an unordered set and initialize it initializer_list
	std::unordered_set<int> setOfNum( { 1, 2, 3, 1, 3, 4, 2 });

	std::unordered_set<int>::const_iterator it = setOfNum.find(4);

	if (it != setOfNum.end()) {
		std::cout << "4 exist in the set" << std::endl;
	}

	it = setOfNum.find(9);

	if (it == setOfNum.end()) {
		std::cout << "9 dont exist in the set" << std::endl;
	}

}

#include <iostream>
#include <unordered_set>
#include <algorithm>

int main() {

	// Create an unordered set and initialize it initializer_list
	std::unordered_set<int> setOfNum( { 1, 2, 3, 1, 3, 4, 2 });

	std::unordered_set<int>::const_iterator it = setOfNum.find(4);

	if (it != setOfNum.end()) {
		std::cout << "4 exist in the set" << std::endl;
	}

	it = setOfNum.find(9);

	if (it == setOfNum.end()) {
		std::cout << "9 dont exist in the set" << std::endl;
	}

}

In the above example we tried to search for the 2 elements in set, one was present and other was not.

Advertisements

Ouput:

4 exist in the set
9 dont exist in the set

 

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top