C++ unordered set Methods

https:/‮w/‬ww.theitroad.com

In C++, the std::unordered_set container provides a number of methods that allow you to manipulate the contents of the set. Here are some of the most commonly used methods:

Inserting Elements

- `insert()`: Inserts a new element into the set.
std::unordered_set<int> mySet;
mySet.insert(1); // Inserts the value 1 into the set

Removing Elements

- `erase()`: Removes an element from the set.
std::unordered_set<int> mySet = {1, 2, 3};
mySet.erase(2); // Removes the value 2 from the set
  • clear(): Removes all elements from the set.
std::unordered_set<int> mySet = {1, 2, 3};
mySet.clear(); // Removes all elements from the set

Finding Elements

- `find()`: Searches the set for an element with a given value, and returns an iterator to the element if found.
std::unordered_set<int> mySet = {1, 2, 3};
auto it = mySet.find(2); // Searches for the value 2 in the set
if (it != mySet.end()) {
  std::cout << "Found: " << *it << std::endl;
} else {
  std::cout << "Not found" << std::endl;
}

Checking the Size of the Set

- `size()`: Returns the number of elements in the set.
std::unordered_set<int> mySet = {1, 2, 3};
std::cout << "Size: " << mySet.size() << std::endl; // Prints "Size: 3"

Iterating over the Elements of the Set

You can use a ranged for loop to iterate over the elements of an unordered set:
std::unordered_set<int> mySet = {1, 2, 3};
for (const auto& elem : mySet) {
  std::cout << elem << " ";
}
std::cout << std::endl;

This will print the elements of the set in no particular order.