To initialize a set in C++, you can use the std::set container from the C++ Standard Template Library (STL).
In this example,
<set>
to access the std::set container from the C++ STL.mySet
, specifying the type of elements it will hold.mySet
by providing initial elements in the constructor.#include <iostream>
#include <set>
int main() {
// Declare and initialize a set
std::set<int> mySet = {1, 2, 3};
// mySet is now initialized with elements 1, 2, and 3
// Example usage:
// Add elements to the set (not applicable in std::set)
// Remove elements from the set (not applicable in std::set)
// Check if an element is present in the set
bool containsElement = mySet.count(2) > 0;
std::cout << "Is element 2 present in the set: " << std::boolalpha << containsElement << std::endl;
return 0;
}
Is element 2 present in the set: true
In this example,
<set>
to access the std::set container from the C++ STL.emptySet
, specifying the type of elements it will hold.emptySet
using the default constructor std::set()
.#include <iostream>
#include <set>
int main() {
// Declare and initialize an empty set
std::set<int> emptySet;
// emptySet is now initialized as an empty set
// Example usage:
// Add elements to the set
emptySet.insert(5);
// Remove elements from the set
emptySet.erase(5);
// Check if an element is present in the set
bool containsElement = emptySet.count(5) > 0;
std::cout << "Is element 5 present in the set: " << std::boolalpha << containsElement << std::endl;
return 0;
}
Is element 5 present in the set: false
In this tutorial, we learned How to Initialize a Set in C++ language with well detailed examples.