Unlocking the Power of C++ STL: Unordered Sets
What is an Unordered Set?
Imagine a collection of unique elements, stored in no particular order, with fast lookup and insertion capabilities. That’s what an unordered set in C++ STL offers. Unlike regular sets, which maintain a specific order, unordered sets prioritize speed and efficiency.
Creating an Unordered Set
To harness the power of unordered sets, you need to include the <unordered_set>
header file. Then, you can create an unordered set using the following syntax: unordered_set<data_type> name;
. For instance, unordered_set<int> numbers;
creates an unordered set to store integers.
Initializing an Unordered Set
There are several ways to initialize an unordered set. You can provide values directly, like this: unordered_set<int> numbers = {1, 100, 2, 9};
. Alternatively, you can copy elements from another unordered set using range initialization.
Example: C++ Unordered Set in Action
Let’s see an unordered set in action:
cpp
unordered_set<int> numbers = {1, 100, 10, 70, 100};
for (auto num : numbers) {
cout << num << " ";
}
Output: 1 10 70 100
(note the absence of duplicates and the arbitrary order)
C++ Unordered Set Methods
The unordered set class offers various methods to perform operations:
Insert Element to an Unordered Set
Use the insert()
method to add elements: numbers.insert(50);
Remove Elements From an Unordered Set
Use the erase()
method to remove elements: languages.erase("Python");
Check If a Value Exists in the Unordered Set
Use the find()
or count()
methods to check for existence:
cpp
if (numbers.find(12)!= numbers.end()) {
cout << "12 exists";
}
cout << "Count of 7: " << numbers.count(7);
Get the Size of the Unordered Set
Use the size()
method to get the number of distinct elements: cout << "Size: " << numbers.size();
With these methods, you can unlock the full potential of unordered sets in C++ STL.