C++ Unordered Set
C++ Unordered Set
In the Sets chapter, you learned that a set stores unique elements, and keeps them sorted.
An unordered_set also stores unique elements, but it does not sort them. Because it does not have to keep the elements in order, it is usually faster to add and find elements, especially when there are many of them.
To use an unordered set, include the <unordered_set> library:
// Include the unordered_set library
#include <unordered_set>
Create an Unordered Set
You create an unordered set in the same way as a set. Like a set, it only stores unique elements. If you add the same value twice, it is only stored once:
Example
unordered_set<string> cars = {"Volvo", "BMW", "Ford", "BMW", "Mazda"};
cout << cars.size();
"BMW" is only stored once, so the size is 4, not 5.
Add and Remove Elements
Use insert() to add an element, and erase() to remove one:
Example
unordered_set<string> cars = {"Volvo", "BMW", "Ford"};
cars.insert("Mazda"); // Add Mazda
cars.erase("Volvo"); // Remove Volvo
cout << cars.size();
Check if an Element Exists
Use count() to check if an element exists. It returns 1 if the element is found, and 0 if it is not:
Example
unordered_set<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};
if (cars.count("BMW")) {
cout << "BMW is in the set";
} else {
cout << "BMW is not in the set";
}
Loop Through an Unordered Set
You can loop through an unordered set with a for-each loop. But remember that the elements come in no particular order:
Example
unordered_set<int> numbers = {10, 20, 30, 40};
int sum = 0;
for (int num : numbers) {
sum += num;
}
cout << "Sum: " << sum;
Set vs. Unordered Set
| set | unordered_set | |
|---|---|---|
| Order of elements | Sorted | No particular order |
| Unique elements | Yes | Yes |
| Speed | Fast | Usually faster |
| Use it when | You need the elements in order | You only need to store and find elements |