How to Declare Comparator For Set of Pair in C++?
Prerequisites:
The set in STL has the property that it stores only the distinct values in the sorted order if the datatype is an integer, in lexicographically smallest to largest if the data type is a string. If the datatype is pair the set keeps the distinct pairs only with the pairs sorted on the basis of the first element of the pair.
The default behavior of the set of pairs can be modified or can be made custom according to our purpose by declaring the custom comparator.
Syntax:
set<pair<data_type_1, data_type_2>, comparator> set_name
Comparator:
struct comparator {
// operator() overloading
bool operator() (const pair<int,int> &p1, const pair<int,int> &p2){
// custom definition code
}
};
Example 1: Declaring a set of pairs with a comparator that keeps the set sorted on the 2nd element of the pair.
C++
#include <bits/stdc++.h>
using namespace std;
struct comp {
bool operator()( const pair< int , int >& p1,
const pair< int , int >& p2) const
{
return p1.second - p2.second;
}
};
int main()
{
set<pair< int , int >, comp> s;
s.insert({ 4, 3 });
s.insert({ 5, 2 });
s.insert({ 6, 1 });
s.insert({ 7, 0 });
for ( auto i = s.begin(); i != s.end(); i++) {
cout << i->first << " " << i->second << endl;
}
return 0;
}
|
Example 2: Declaring a set of pairs with a comparator that keeps the set sorted on the basis of the difference between the first and second elements of the pair.
C++
#include <bits/stdc++.h>
using namespace std;
struct comp {
bool operator()( const pair< int , int >& p1,
const pair< int , int >& p2)
{
int diff1 = p1.first - p1.second;
int diff2 = p2.first - p2.second;
return diff1 < diff2;
}
};
int main()
{
set<pair< int , int >, comp> s;
s.insert({ 4, 3 });
s.insert({ 5, 2 });
s.insert({ 6, 4 });
s.insert({ 7, 3 });
for ( auto i = s.begin(); i != s.end(); i++) {
cout << i->first << " " << i->second << endl;
}
return 0;
}
|
Example 3: Given a set of pairs with the pair’s first element as the char and 2nd element as the rank of the character declare a custom comparator that stores the order as descending order of rank if the race between the same first element occurs.
C++
#include <bits/stdc++.h>
using namespace std;
struct comp {
bool operator()( const pair< char , int >& p1,
const pair< char , int >& p2)
{
if (p1.first == p2.first) {
return p1.second > p2.second;
}
return p1.first < p2.first;
}
};
int main()
{
set<pair< char , int >, comp> s;
s.insert({ 'a' , 3 });
s.insert({ 'c' , 2 });
s.insert({ 'c' , 4 });
s.insert({ 'c' , 5 });
s.insert({ 'b' , 4 });
s.insert({ 'b' , 3 });
for ( auto i = s.begin(); i != s.end(); i++) {
cout << i->first << " " << i->second << endl;
}
return 0;
}
|
Output
a 3
b 4
b 3
c 5
c 4
c 2
Last Updated :
11 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...