Create & Initialize a Set in C++

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++.

How to create an Empty Set?

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.

How to Initialize a Set using Initializer List?

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};

How to Initialize a Set from Another Set?

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);

How to Initialize a Set from a Range?

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]));

Key Points to Remember while using Set in C++

  1. Elements in a std::set are always sorted.
  2. Duplicate values will be ignored, ensuring each value in the set is unique.

Summary

We learned how to create and initialize a std::set in C++.

Scroll to Top