We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

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.

Advertisements

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.

Ouput:

4 exist in the set
9 dont exist in the set

 

Cart

Your Cart is Empty

Back To Shop