In C++, std::set
is a associative container provided by the Standard Template Library (STL). It represents a collection of unique elements, stored in a sorted order. In this tutorial, we will explore various ways to create and initialize a std::set
object in C++.
To create an empty set object, you can simply declare it with its type:
#include <iostream> #include <set> int main() { std::set<int> setObject; std::cout << "Size of the set: " << setObject.size() << std::endl; return 0; }
Here, we’ve created a set of integers named setObject
. Since it’s an empty set, its size is 0, indicating that there are no elements in it. The Set class provides a size()
function to retrieve the number of elements in the set.
C++11 introduced the initializer list. We can pass this to the set constructor to initialize the set object.
std::set<int> setObject = {1, 2, 3, 4, 5};
A set can be initialized using the contents of another set, like this,
std::set<int> setObject = {1, 2, 3, 4, 5}; std::set<int> anotherSet(setObject);
You can also initialize a set using a range of elements. Range can be an array or any other container, like this,
int arr[] = {1, 2, 3, 4, 5}; std::set<int> setObject(arr, arr + sizeof(arr)/sizeof(arr[0]));
std::set
are always sorted.We learned how to create and initialize a std::set
in C++.