154 views
Unordered Set in C++
The C++ std::unordered_set
is a container in the C++ Standard Library that represents an unordered set of unique elements. It is similar to std::set
, but unlike std::set
, it does not maintain elements in a sorted order; instead, it uses a hash-based data structure to store elements for faster access times. Here’s how to use std::unordered_set
:
C++
#include <iostream>
#include <unordered_set>
int main() {
// Create an unordered_set of integers
std::unordered_set<int> mySet;
// Insert elements into the set
mySet.insert(42);
mySet.insert(17);
mySet.insert(99);
// Check if an element is in the set
if (mySet.find(17) != mySet.end()) {
std::cout << "17 is in the set." << std::endl;
}
// Iterating through the elements of the set
for (const auto& element : mySet) {
std::cout << element << " ";
}
std::cout << std::endl;
// Erase an element from the set
mySet.erase(42);
// Size of the set
std::cout << "Size of the set: " << mySet.size() << std::endl;
return 0;
}
In the code above:
- We include the
<unordered_set>
header to usestd::unordered_set
. - We create an
std::unordered_set<int>
calledmySet
. - We insert elements using the
insert
function. - We check if an element is in the set using the
find
function. - We iterate through the elements of the set using a range-based
for
loop. - We erase an element from the set using the
erase
function. - We determine the size of the set using the
size
function.
Keep in mind that std::unordered_set
provides fast average time complexity for insertion, deletion, and search operations, typically O(1). However, the order of elements is not guaranteed, as it depends on the hash values of the elements. If you need elements in a sorted order, you might want to use std::set
instead.