Browse by Domains

Set in C++ – A Complete Reference

C++ has got many useful elements and tools that help us in competitive programming. One of such components is sets present in the Standard Template Library (STL), which provides a way to store data in a sorted manner efficiently. This guide to set in C++ covers all the essentials that you need to know about sets. 

Sets are the containers in C++ STL for storing elements in a given order. The elements of a set must be unique. The value itself can identify each element in a set, i.e., they act as keys themselves. We can insert elements in or remove elements from a set in C++ but cannot modify them since the values become constant once stored in the set. You will know more about sets in C++ as you follow through this article, starting right from what is set in C++ and going all the way to Interlinks.

What is Set in C++?

As mentioned above, sets in C++ are the type of STL containers that are used for storing elements in a sorted way. The operations allowed to be performed on sets are insertion and deletion. The elements are internally sorted according to a strict weak ordering in a set type container. Since the elements in the containers are constant, we cannot manipulate or manipulate the values of the existing elements in a set. An element in a set acts as a key for itself by identifying it uniquely. Hence, sets are only allowed to hold unique values.  

In order to traverse sets in C++, we make use of iterators. <set> and <iterators> are the two header files that must be included in order to work with sets in C++. An alternative to these two header files is <bits/stdc++>.  The internal implementation of sets is done with the use of Binary Search Trees (BSTs).

When to use sets?

Sets are frequently used containers in competitive programming; whenever there is a need of storing the elements in a sorted manner, we can think of using the sets, but remember that the set does not allow us to store the duplicates value. The value can’t be modified once it is stored. 

Implementing sets

  • Sets are traversed using the iterators. 
  • We have to include the two main header files to work with the sets.

#include< set >

#include< iterator >

  •   Instead of using the above two header files, we can also use only this one header file.

             This one header file contains all the header file , so we can only use this one header file ,     

             instead of all the other header files .

          #include< bits/stdc++.h >

  • begin() :- Returns an iterator to the first element of the set .
  • end() :- Returns an iterator to the theoretical element that follows last element in the set .
  • Empty() :- check wheather the set is empty or not .
  • max_size() :-Returns the maximum number of element that set can hold .
  • Size() :- Returns the number of elements in the set .

Initialising a set in C++

We define the type of values to be stored in a set at the time of its initialisation in C++. By default, the numeric values in a set are stored in increasing order. If we want to store in decreasing order, we can use greater<int>. We can initialise a set in multiple ways:

  • Empty set
  • Set with Values
  • Set initialised with another Set
  • Set initialised with an Array.

Here is an example to describe the initialisation and printing of a set in C++.

#include<iostream>
#include<set>

using namespace std;
 
int main()
{
 
    // Empty Set
    set<int> set1;
    // set1 = {}
 
    // Empty Set - Decreasing Order
    set<int, greater<int>> set2;
    // set2 = {} 
 
    // Set with values
    set<int, greater<int>> set3 = {6, 10, 5, 1};
    // set3 = {10, 6, 5, 1}
 
    // Initialize Set using other set
    set<int, greater<int>> set4(set3);
    // set4 = {10, 6, 5, 1} 
 
    // Initializing a set from array
    int arr[] = {10, 4, 5, 61};
    set<int> set5(arr, arr+4);  // Since the array has four elements, thus arr+4 

     // Defining iterator for the set
    set<int> :: iterator it;

    //Printing a set using for loop – (1)
    for (auto it = set5.begin(); it!=set5.end();it++)
    {
        cout<<endl<<*it;
    }
    return 1;
}

Output:

4

5

10

61

In the above example, different ways of initializing a set in C++ has been shown. For displaying the set, we use a for loop along with begin() and end() functions to get the location of the first and last element of a set. We have used the iterator ‘it’ to iterate on the set5. This iterator iterates on the position of elements in the set. Since the order of integer elements in a set is ascending by default, the array elements, when stored in set5, get sorted in increasing order, as seen in the output.

Properties of set in C++

Some of the common properties of sets in C++ have been given below:

  • The property of Uniqueness: Every element of a set in C++ must be unique, i.e., no duplicate values are allowed. Hence, we can say that sets in C++ do not favor redundancy.
  • The property of being Sorted: The elements in a set container are automatically stored in a sorted manner.
  • The property of being Immutable: You cannot change the values once they are stored in a set. Hence, insertion and deletion are allowed, but you cannot update or modify the existing elements of the set. 
  • The property of Internal Implementation: The logical implementation of a set in C++ is done using a BST. 

The property of Unindexing: Since C++ STL does not provide support for indexing, the sets in C++ are also unindexed.

Code for implementing set in C++:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    set < int > s;
 
    // inserting elements in random order .
    s.insert( 60 ) ;
    s.insert( 10 ) ;
    s.insert( 20 ) ;
    s.insert( 20 ) ;
    s.insert( 40 ) ;
    s.insert( 50 ) ;
    
    // printing set s
    //initialising the iterator, iterating to the beginning of the set.

    set<int >::iterator it ;
    cout << "The element of set s are : \n";
    for (it = s.begin() ; it != s.end() ; it++ ) 
    {
        cout << *it<<" ";
    }
    cout << endl;
    
    cout<< ”The size of set : \n ” << s.size() <<endl ;
    return 0 ;
}
     

Output:

    The element of set s are :

    10 20 40 50 60 

    The size of set : 5

  •  To store the elements in decreasing order in the set.

    By default, elements are stored in ascending sorted order in the set. To store the elements in descending order, we have to use the given declaration syntax.

           // declaration syntax of the set to store the elements in decreasing sorted order.

     set<int,greater<int>> s;

find() :-

Returns an iterator pointing to the element, if the element is found else return an iterator 

pointing to the end of the set.

Syntax:

set_name.find( key ) ;

erase() :-

this method is used to delete the elements from the set

Syntax:

set_name.erase( starting_iterator , ending_iterator ) ;

Implementation code of set in c++ :-

#include<bits/stdc++.h>
using namespace std;
int main()
{
set< int >s ;
s.insert( 34 ) ;
s.insert( 14 ) ;
s.insert( 13 ) ;
s.insert( 56 ) ;
s.insert( 5 ) ; 
s.insert( 23 ) ;
s.insert( 10 ) ;
s.insert( 4 ) ;
set<int> :: iterator it;
cout<<”the elements of set are : \n“;
for(it = s.begin() ; it != s.end() ; it++)
{
cout<<*it<< ” “;
}
cout<< endl ;

// Removing all elements upto 10
cout<< ” elements of set s after deleting elements upto 10  \n ” ;
s.erase(s.begin() , s.find(10) ) ;
for ( it = s.begin() ; it!=s.end() ; it++)
cout<< *it << ” “ ;
// Performing Lower bound and upper bound in set
cout<< ” lower bound of 13 \n ” ;
cout<< *s.lower_bound(13)<<endl;
cout<< ” lower bound of 34\n ” ;
cout<< *s.lower_bound( 34 ) << endl;
cout<< ” upper bound of 13 \n ” ;
cout<< *s.upper_bound( 13 ) <<endl;
cout<< ”upper bound of 34  \n” ;
cout<< ”*s.upper_bound( 34 ) <<endl ;
return 0;
}

Output:- 

the elements of set are :

4 5 10 13 14 23 34 56

elements of set s after deleting the elements upto 1

10 13 14 23 34 56

lower bound of 13

13

lower bound of 34

34

upper bound of 13

14

upper bound of 34

56

Methods on set

There is a wide range of operations that can be performed on sets in C++. Let us look at some of the vital methods of sets.

  1. begin():  This method returns an iterator that points to the first element in the set.
  2. end(): This function returns an iterator that points to the theoretical position next to the last element of the set.
  3. empty(): This set method is used for checking whether the set is empty or not.
  4. size(): This function gives the number of elements present in a set .
  5. max_size(): This method returns upper bound of elements in a set, i.e. the maximum number that a set can hold.
  6. rbegin(): In contrary to the begin() method, this method returns a reverse iterator pointing to the last element of a set.
  7. rend(): In contrary to the begin() method, this method returns a reverse iterator pointing to the logical position before the last element of a set.
  8. erase (iterator_position): This method when applied  on a set, removes the element at the position pointed by the pointer given in the parameter.
  9. erase (const_n): This function directly deletes the value ‘n’ passed in the parameter from a set .
  10. insert (const_n): This function inserts a new element ‘n’ into the set .
  11. find( n ): This method searches for the element ‘n’ in the set and returns an iterator pointing to the position of the found element. If the element is not found, it returns an iterator pointing at the end.
  12. count( const_n ): This set method checks for the occurrence of the passed value ‘n’ and returns 0 or 1 if the element is found or not found respectively.
  13. clear(): It removes all the elements present in a set.  

Take a look at the following piece of C++ code to understand the implementation of above methods better.

// Online C++ compiler to run C++ program online
#include<iostream>
#include<set>

using namespace std;
 
int main(){
 
    set<int> s = {10, 12, 15, 6};
    set<int> :: iterator it;
    cout<<"First element is:"<<*(s.begin());     // begin()
    cout<<"\nLast element is:"<<*--(s.end())<<endl;   // end()

     // Traversal()
    for (auto it = s.begin(); it!=s.end(); it++)
    {
        cout<<" "<<*it;
    }
    cout<<endl;
    
    if(s.empty())    // empty()
    cout<<"Empty";
    else
    cout<<"Not empty";
    
    cout<<"\nSize of the set: "<<s.size();                 // size()
    
    cout<<"\nMax Size: "<<s.max_size();              //max_size()
    
    s.erase(s.begin());                    // erase(iterator)
    s.erase(12);                             // erase(n)
    cout<<"\nAfter removing the first element and the element 12: ";
    for (auto it = s.begin(); it!=s.end(); it++)
    {
        cout<<" "<<*it;
    }
    
    s.insert(5);                         // insert(n)
    cout<<"\nAfter inserting the new element 5: ";
    for (auto it = s.begin(); it!=s.end(); it++)
    {
        cout<<" "<<*it;
    }
    
    if(s.count(15)==1)
    cout<<endl<<"15 is present in the set";
    else
    cout<<endl<<"15 i not present";
    
    s.clear();                            // clear()
    if(s.empty())
    cout<<"\nNow, the set is empty";
    else
    cout<<"\nSet is not empty";
    return 0;
}

Output:

First element is: 6
Last element is:15
6 10 12 15
Not empty
Size of the set: 4
Max Size: 230584300921369395
After removing the first element and the element 12: 10 15
After inserting the new element 5: 5 10 15
15 is present in the set
Now, the set is empty

Difference between set, multiset, and unordered_set

Parameterssetmultisetunordered_set
Storage OrderStores elements in a sorted mannerStores elements in a sorted manner – in increasing or decreasing orderStores elements in an unsorted order
Type of elementsHolds unique elements onlyIt can hold duplicate valuesOnly unique values are allowed
ModificationInsertion and deletion of elements are possible, but modification of elements is not allowedDeletion of elements can be done with the help of iteratorsInsertion and deletion of elements are possible, but modification of elements is not allowed
ImplementationImplemented internally via Binary Search Trees Internal implementation through Binary Search TreesImplemented internally using Hash Tables
Erasing elementMore than one elements can be erased by giving the starting and ending iteratorWe can erase that element for which the iterator position is given We can erase that element for which the iterator position is given
Syntaxset<datatype> setNamemultiset<datatype> multiSetName;unordered_set<datatype> UnorderedSetName;

set:

  • A Set stores the elements in sorted order.
  • Set stores unique elements.
  • Elements can only be inserted and deleted but cannot be modified within the set.
  • Sets are implemented using a binary search tree.
  • Sets are traversed using iterators.

C++ program showing insertion and deletion functioning in the set.

#include<bits/stdc++.h>
using namespace std;
int main()
{
// declaring set.
set< int > s ;
// adding random elements to set using the insert().
s.insert( 13 ) ;
s.insert( 11 ) ;
s.insert( 44 ) ;
s.insert( 1 ) ;
s.insert(10 ) ;
s.insert( 25 ) ; 
s.insert( 11 ) ;   // 11 will only be added only once .  
// declaring iterators to traverse through the set .
set <int> s :: iterator ptr1 , ptr2 , ptr3 ;
cout << “ set elements are initially  : \n” ;
for ( ptr1 = s.begin() ; ptr1 != s.end() ; ptr1++)
{
 cout<< *ptr1 << “ “ ;
}
cout <<endl ;
// making another set  s2 , storing elements in decreasing order.
// copying the elements of s into s2 .
set < int , greater <int> > s2 ( s.begin()  , s.end() ); 
set < int , greater <int > > :: iterator itr ; 
ptr2 = s.find( 11 ) ;
ptr3 = s.find( 25) ;
// elements from 11 to 25 are erased from the set using the erase() . 
s.erase ( ptr2 , ptr3);
cout << ”  set element after erase  : \n ” ;
for ( ptr1 = s.begin() ; ptr1 != s.end() ; ptr1++)
{
cout << *ptr1 << “ “;
}
cout << endl ;
cout << “ elements of set s2 are : \n” ;
for ( itr = s2.begin() ; itr != s2.end()  ; itr++)
{
cout << *itr << “ “;
}    
return 0;
}

Output : 

set elements are initially :

1 10 11 13  25 44

set elements after erase :

1  10 25 44

elements of set s2 are :

44 25 13 11 10 1

Multiset :

  • It also stores the elements in a sorted manner, either ascending or decreasing.
  • Multiset allows storage of the same values many times; or, in other words, duplicate values can be stored in the multiset.
  • We can delete the elements using iterators.

       Note: – All other properties of a multiset are the same as that of the set, the difference       

                   being it allows storage of the same multiple values.

C++ program showing implementation of multiset.

#include<bits/stdc++.h>
using namespace std ;
int main()
{
// declaring multiset.
multiset < int > ms;
// elemets added to multiset . 
ms . insert ( 14 ) ;
ms . insert ( 10 ) ;
ms . insert ( 20 ) ;
ms . insert ( 5 )  ;
ms . insert ( 14 ) ;    // duplicate element added . 
ms . insert ( 25 ) ;
ms . insert ( 25 ) ;   //  duplicate element added . 
ms . insert ( 29 ) ;

// declaring iterators to traverse the mutiset.
multiset < int > :: iterator it1 , it2 , it3 ;
cout << “ elements of multiset are : \n” ;
for ( it1 = ms.begin() ; it1 != ms.end() ; it1++)
{
cout << *it1 << “ “ ;
}

it2 = ms.find ( 10 ) ;
it2 = ms.find ( 25 ) ;
// removing  the elements of multiset from 10 to 25 (exclusive) . 
ms.erase ( it1 , it2 ) ;
cout << “ elements of multiset after removing the elements : \n ” ;
for ( it1 = ms.begin() ; it1 != ms.end() ; it1++ )
{
cout<< *it1 << “ “ ;
}
return 0 ; 
}

Output :

elements of multiset are :

5 10 14 14 20 25 25 29

elements of multiset after removing the elements :

5 25 25 29

Conclusion:  multiset allows storing duplicate values, whereas set doesn’t.

Unordered_Set :

  • Unordered_set can stores elements in any order, with no specified order for storing elements. It generally depends upon the machine that you are using.
  • Stores unique elements, no duplicates allowed.
  • unordered_set uses the hash table for storing the element.

Note: All other properties are the same as that of the set.

C++ program showing implementation of set.

#include<bits/stdc++.h>
using namespace std;
int main()
{
// declaring unordered_set .
unordered_set < int > us;
// adding elements to unordered_set  . 
us . insert ( 14 ) ;
us . insert ( 10 ) ;
us . insert ( 20 ) ;
us . insert ( 14 ) ;   // duplicates added .
us . insert ( 12) ;
us . insert ( 8 ) ;
unordered_set < int > :: iterator it1 , it2 ;
cout << “ elements of unordered_set are \n “ ;
for ( it1 = us.begin() ; it1 != us.end() ; it1++ )
{
cout <<  *it1 << ” “ ;
}
// erasing element 14 
it2 = us.find ( 14 ) ;
us.erase( it2 ) ;
cout<< “ elements of unordered_set after erasing the element : \n ” ;
for(  it1 = us.begin() ; it1 != us.end() ; it1++ )
{
cout << *it1 << “ “ ;
} 
return 0;
}

Output :

elements of unordered_set are :

14 10 20 12 8   

elements of unordered_set after erasing the element :

10 20 12 8 

Note:- Don’t compare the order of output produced by printing the unordered_set with anyone because it can be different for everyone depending upon their machine, etc. 

What is setprecision in C++?

C++ offers a bunch of manipulators that are used to format the data types. One of such manipulators is setprecision in C++. It sets the floating-point precision of decimal numbers on the output screen. One might sometimes confuse setprecision function with other set operations or functions in C++, but they are completely different. C++ allows us to set the decimal places as described in the following section.

How to set decimal places in C++?

We use the setprecision() method in order to set the precision of floating point numbers. In other words, this method enables us to decide how many total digits to be displayed and hence puts a limit on the number of post-decimal-point digits to be displayed. The syntax followed by an example has been given below.

Syntax:

setprecision (n)

Here, the argument ‘n’ is the number of significant figures to be displayed on the output screen in the case of a floating point literal.

Example:

#include <iostream>
#include <iomanip>

using namespace std;

int main() 
{
  
  float a = 5.912346;    // Initializing a floating-point variable

  cout << "The actual number is: " << a<< endl;

  cout << "The number with 4 significant figures is: "; 

  cout << setprecision(4) <<a;  
  // This will print 4 significant figures on the screen

  return 0; 
}

Output

The actual number is: 5.91235
The number with 4 significant figures is: 5.912

Conclusion

In simple words, Set is an STL container that stores sorted ( ascending or descending  ) and unique elements inside it. Multiset also stores the element in a sorted manner, but it can also store duplicate values. Unordered_Set stores the element in any manner, but it doesn’t store the identical values.

This brings us to the end of the blog on the concept of Set in C++. We hope that you found this comprehensive and helpful and were able to gain the required knowledge. If you wish to up-skill and learn more such concepts, you can check out the pool of Free online courses on Great Learning Academy and Online Software Engineering Courses.

Also, if you are preparing for Interviews, check out these Interview Questions for C++ to ace it like a pro.


Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top