In C++, you can use the std::set container to represent a Set. To add an item to a Set, you can use the insert() method provided by the std::set class.
In this example,
numbers
containing some integer elements.numbers
to add a new integer element, such as 6
, to the set.numbers
contains the added element 6
.#include <iostream>
#include <set>
int main() {
std::set<int> numbers = {1, 2, 3, 4, 5};
numbers.insert(6);
std::cout << "Numbers: { ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << "}";
return 0;
}
Numbers: { 1 2 3 4 5 6 }
In this example,
fruits
containing some string elements.fruits
to add a new string element, such as 'Orange'
, to the set.fruits
contains the added element 'Orange'
.#include <iostream>
#include <set>
#include <string>
int main() {
std::set<std::string> fruits = {"Apple", "Banana", "Cherry"};
fruits.insert("Orange");
std::cout << "Fruits: { ";
for (const std::string& fruit : fruits) {
std::cout << fruit << " ";
}
std::cout << "}";
return 0;
}
Fruits: { Apple Banana Cherry Orange }
In this tutorial, we learned How to add an Item to a Set in C++ language with well detailed examples.