In C++, sets are associative containers that store unique elements in some sorted order. By default, set store data in increasing order but we can change this using a custom comparator. In this article, we will learn, how to declare a set with a custom comparator in C++ STL.
Example
Input: Data = {1, 5, 3, 4, 2} Output: mySet = {5, 4, 3, 2, 1}
Declare a Set with a Custom Comparator in C++
To declare a set with a custom comparator in C++, we have to pass the comparator function to the set at the time of its declaration. This function will then be used to determine the order of elements in the set.
Syntax
std::set<T, Compare_Type> mySet;
Here, T is the type of elements in the set, and Compare is the type of the comparator.
C++ Program to Declare a Set with a Custom Comparator
// C++ Program to illustrate how to declare a set with a // custom comparator #include <cmath> #include <iostream> #include <set> using namespace std;
// Custom comparator for sorting integers based on absolute // values struct AbsoluteValueComparator {
bool operator()( int a, int b) const
{
return abs (a) < abs (b);
}
}; int main()
{ // Declare a set of integers with the custom comparator
set< int , AbsoluteValueComparator> mySet;
// Insert elements into the set
mySet.insert(-5);
mySet.insert(3);
mySet.insert(-8);
mySet.insert(2);
// Print the elements in the set (sorted based on
// absolute values)
cout << "Elements in the set: " ;
for ( int element : mySet) {
cout << element << " " ;
}
return 0;
} |
Elements in the set: 2 3 -5 -8