The Standard Template Library (STL) contains in-built data-structures that come in handy while implementing complex algorithms. One of these containers is a “Set”.

Properties of a Set in C++

Let us walk through some basic properties of a C++ Set before moving onto its implementation.

  • Uniqueness – All elements inside a C++ Set are unique.
  • Sorted – The elements inside a Set are always in a sorted manner.
  • Immutable – Any element inside the Set cannot be changed. It can only be inserted or deleted.
  • Unindexed – The STL Set does not support indexing.
  • Internal Implementation – The Sets in STL are internally implemented by BSTs (Binary Search Trees).

Initializing a Set in C++

The initialization of a Set involves defining the data type for the elements to be stored and the order in which they are to be stored.

#include<iostream>
#include<set>
/*
Or

#include<bits/stdc++.h>
*/
using namespace std;

int main(){

	// Empty Set - Increasing Order (Default)
	set<int> s1;
	// s1 = {}

	// Empty Set - Decreasing Order
	set<int, greater<int>> s2;
	// s2 = {} 

	// Set with values
	set<int, greater<int>> s3 = {6, 10, 5, 1};
	// s3 = {10, 6, 5, 1}

	// Initialize Set using other set
	set<int, greater<int>> s4(s3);
	// s4 = {10, 6, 5, 1} 

	// Initializing a set from array
	int arr[] = {10, 4, 5, 61};
	set<int> s5(arr, arr+2);  // Only two elements 
	// s5 = {4, 10}

	return 1;
}

The above code snippet explains the methods of initializing a STL Set.


Traversing a Set in C++

C++ has a concept of iterators for each specific STL data structure. Since a Set does not support indexing, we need to define iterators to fetch its elements.

#include<iostream>
#include<set>

using namespace std;

int main(){

	// Set with values
	set<int, greater<int>> s1 = {6, 10, 5, 1};

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

	// Print the elements of the set
	for(it=s1.begin(); it != s1.end();it++)
		cout<<*it<<" ";
	cout<<endl;
}

Output:

10 6 5 1 

Few things to note here are:

  • **'begin()'** – This function returns an iterator to the first element.
  • **'end()'** – This function returns an iterator past the last element.
  • **'*it'** – The value stored in the position iterator points to.

#c++ #programming-c #cplusplus

Set in C++ STL - The Complete Reference
1.55 GEEK