C++ Remove Elements From an Unordered Set

h‮/:sptt‬/www.theitroad.com

To remove elements from an std::unordered_set container in C++, you can use the erase() method. Here are a few examples:

#include <iostream>
#include <unordered_set>

int main() {
    std::unordered_set<int> mySet = {1, 2, 3, 4, 5};

    // Remove a single element
    mySet.erase(3);

    // Remove multiple elements using an initializer list
    mySet.erase({4, 5});

    // Remove elements using a range of iterators
    std::vector<int> vec = {1, 2};
    mySet.erase(vec.begin(), vec.end());

    // Print the contents of the set
    for (const auto& elem : mySet) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;

    return 0;
}

This program creates an std::unordered_set container called mySet with the values 1, 2, 3, 4, and 5. It then demonstrates how to remove elements from the set using various methods. Finally, it prints the contents of the set to the console. The output of this program will be:


Note that the output is empty because all the elements have been removed from the set.