In this tutorial, we will explore the unordered_set and unordered_multiset containers in C++. These are hash-based sets that provide average O(1) time complexity for insertions, deletions, and lookups. Understanding these containers is crucial for scenarios where fast access to elements is required, but order does not matter.
The unordered_set and unordered_multiset containers are part of the Standard Template Library (STL) in C++. They store unique elements (unordered_set) or multiple occurrences of the same element (unordered_multiset). The key advantage of these containers is their average constant time complexity for operations like insertion, deletion, and lookup. This makes them highly efficient for scenarios where order does not matter.
In this tutorial, we will cover:
unordered_set and unordered_multiset.unordered_set and set.Both unordered_set and unordered_multiset are templated classes that require a type parameter. They also allow for specifying a hash function, equality comparator, and allocator.
The unordered_set container stores unique elements. Here is the basic syntax:
1#include <iostream>2#include <unordered_set>34int main() {5std::unordered_set<int> mySet = {10, 20, 30};67// Inserting elements8mySet.insert(40);910// Checking if an element exists11if (mySet.find(20) != mySet.end()) {12std::cout << "Element found!" << std::endl;13}1415// Removing an element16mySet.erase(30);1718// Iterating over elements19for (const auto& elem : mySet) {20std::cout << elem << " ";21}22return 0;23}
You can specify a custom hash function when declaring an unordered_set. This is useful when you want to define how elements are hashed.
1#include <iostream>2#include <unordered_set>3#include <string>45struct MyHash {6std::size_t operator()(const std::string& key) const {7return std::hash<std::string>{}(key);8}9};1011int main() {12std::unordered_set<std::string, MyHash> mySet = {"apple", "banana", "cherry"};1314// Inserting elements15mySet.insert("date");1617// Checking if an element exists18if (mySet.find("banana") != mySet.end()) {19std::cout << "Element found!" << std::endl;20}2122// Iterating over elements23for (const auto& elem : mySet) {24std::cout << elem << " ";25}26return 0;27}
unordered_set when order is not important and you need fast access. Use set when maintaining a sorted order is necessary.In the next tutorial, we will explore iterators in C++. Iterators provide a way to traverse through elements of containers like unordered_set and unordered_multiset. Understanding iterators is essential for efficient manipulation and traversal of container elements. Stay tuned!