To remove a specific item from a set in C++, you can use the erase method to delete the item from the set.
In this example,
numberSet
using the std::set
container from the C++ Standard Library, which contains integer values 1
, 2
, 3
, 4
, and 5
.erase
method of numberSet
to remove the item 3
from the set.numberSet
to see the removed item.#include <iostream>
#include <set>
int main() {
std::set<int> numberSet = {1, 2, 3, 4, 5};
numberSet.erase(3);
for (int num : numberSet) {
std::cout << num << " ";
}
return 0;
}
1 2 4 5
In this example,
stringSet
using the std::set
container from the C++ Standard Library, which contains string values 'apple'
, 'banana'
, 'cherry'
, 'date'
, and 'grape'
.erase
method of stringSet
to remove the item 'cherry'
from the set.stringSet
to see the removed item.#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> stringSet = {"apple", "banana", "cherry", "date", "grape"};
stringSet.erase("cherry");
for (const std::string& str : stringSet) {
std::cout << str << " ";
}
return 0;
}
apple banana date grape
In this tutorial, we learned How to Remove Specific Item from a Set in C++ language with well detailed examples.