How to use Set in C++
Introduction
“An associative (STL) container, a set in the programming language C++, is used to store distinct elements organized in an increasing or decreasing order.”
Every value in the set functions as a key, making each element distinct and the Set not supporting indexing. As a result, none of the duplicate values may be stored within the Set. As a result, there can only be one index, and the elements and values (keys) act as indexes themselves. Additionally, the Set's values can only be retrieved using their respective keys and values.
The Set's elements are likewise kept in sorted order. During the set definition, we can define whether the components will be arranged in ascending or descending order by modifying the syntax.
The element in a set can be added, removed, and searched with logarithmic time complexity. When an element is added to a set, it becomes a constant and cannot be changed (the value cannot be changed). The binary search tree (Red-Black Tree) is utilized internally by C++ to implement the set STL.
Syntax
To define a set, we must first utilize the STL set. Then, in the angle brackets (<>), we must specify the data type of the Set's elements and, lastly, the Set's name.
set<datatype> name_of_set;
If you want the Set to store the components in a decreasing sequence instead of ascending order by default, you must write greater <datatype> alongside the data type.
Example
#include<iostream>
#include<set>
#include<string>
int main()
{
std::set<std::string> setOfNumbers;
setOfNumbers.insert("first number");
setOfNumbers.insert("second number");
setOfNumbers.insert("third number");
std::cout<<"Set Size = "<<setOfNumbers.size()<<std::endl;
for (std::set<std::string>::iterator it=setOfNumbers.begin(); it!=setOfNumbers.end(); ++it)
std::cout << ' ' << *it;
std::cout<<"\n";
return 0;
}
Output
![How to use Set in C++](https://static.tutorialandexample.com/cpp/how-to-use-set-in-cpp1.png)
The advantages and features of std::set
It only contains unique elements and doesn't permit duplicating any elements.
Std::set stores elements internally in a balanced binary tree and can accept elements of any type given in the template argument.
std::set<int> // contains only int elements.
class Sample;
std::set<Sample> // contains only Sample class objects.
By default, std::set uses the comparison operator to compare two variables, but if the user meets an external sorting criterion, such as a comparison, that operator is used instead.
Assigned sorting criteria, such as the standard criteria operator or a supplied comparison (if passed), will be used by std::set to maintain the order of the inserted elements.
How to use std::search to find an element set
Utilizing the find member function,
iterator find (const value_type and val) const;
If an element matching val is found, it searches the container's contents for it and returns an iterator to it; if not, it provides an iterator to set::end.
Example
#include<iostream>
#include<set>
#include<string>
int main()
{
std::set<std::string> setOfNumbers;
set of numbers.insert("first number");
set of numbers.insert("second number");
set of numbers.insert("third number");
setOfNumbers.insert("first")
std::set<std::string>::iterator it = set of numbers.find("second number");
if(it != set of numbers.end())
std::cout<<"'first element' found"<<std::endl;
else
std::cout<<"'first element ' not found"<<std::endl;
it = set of numbers.find("fourth");
if(it != set of numbers.end())
std::cout<<"'fourth' found element"<<std::endl;
else
std::cout<<"'fourth element ' not found"<<std::endl;
return 0;
}
Output
![How to use Set in C++](https://static.tutorialandexample.com/cpp/how-to-use-set-in-cpp2.png)
Set Functions
begin()
It returns an iterator referring to the first member of the set end with the begin() function. () gives back a pointer to the area that is immediately after the Set's final element.
rbegin()
The reverse iterator referring to the final element is returned by the begin () function.
rend()
provides a reverse iterator with a pointer to the position preceding the first element.
Example
#include<bits/stdc++.h>
using namespace std;
int main()
{
set<int> s = {34,45,34,75,64,84,9,6,77,13,66,54};
set < int > ::iterator it;
it = s.begin();
cout << "using begin() = " << * it << "\n";
it = s.end();
it--;
cout << "using end() = " << * it << "\n";
set < int > ::reverse_iterator rit;
rit = s.rbegin();
cout << "using rbegin() = " << * rit << "\n";
rit = s.rend();
rit--;
cout << "using rend() = " << * rit << "\n";
return 0;
}
Output
![How to use Set in C++](https://static.tutorialandexample.com/cpp/how-to-use-set-in-cpp3.png)
Explanation
In this example, we constructed an iterator it after generating the Set s.
We first used the Set.begin() function to allocate it a pointer to the first element in the Set, and then we used the dereference operator to output the value for the check. The set.end() function was subsequently utilized to assign an iterator to point to the Set's final element.
We created the reverse iterator "rit" to make use of the rbegin() and rend() operations. and after that, we directed the iterator to go to the first element from the rear and the last one from the back of the Set using the Set.rbegin() and set.rend() functions.
Conclusion
The elements that make up the Set can be added or taken away, but they cannot be changed once they are added.
When we need to keep distinct elements (i.e., values without duplicates) and store them in a particular order, we utilize sets, which are standard template library (STL) containers in C++.