Reputation: 2027
I have a
pair<int, pair<int, string> >.
Now, I am inserting this into a STL Set of c++. It keeps the set sorted by the first value. But, if I insert a pair which has the same first value as some other, I want this to be sorted according to the second value according to larger first. I will give an example to make it clear.
#define pii pair<int, string>
#define pint pair< int , pii >
set< pint > S;
set< pint >::iterator it;
S.insert(make_pair(100, make_pair(1, "hi")));
S.insert(make_pair(50, make_pair(2, "hello")));
it = S.begin();
cout << it->second.second;
Here the output I get is
hello
But, now if I do,
S.insert(make_pair(50, make_pair(3, "dude")));
it = S.begin();
cout << it->second.second
Here also the output is
hello
But I want the output to be
dude
Because it's first value(50) is smaller than "hi"'s first value(100) and equal to "hello"'s first value(50). But, it's second value(3) is greater than "hi"'s second value(1) and also greater than "hello"'s second value.
Thank you.
Thus, if the first value is same then it must sort according to the second value but in larger second value first.
Upvotes: 1
Views: 2484
Reputation: 3261
As you can see, the definition of set
allows you to specify a comparison operation
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> > class set;
Compare
can be a class which has an operator()
that does the comparison. This operator takes two values, and needs to return true
if the first is to be placed before the second in the set.
Upvotes: 3