sorting a vector of pairs:

i am sorting a vector of pairs.
and the pair is pair<int,char>
when i am sorting the vector, it is sorting in ascending order having int as primary key and char as secondary key.

but i require the output :: it has to sort it in ascending order based on primary key and in descending order based on secondary key

----------------------------------
is there any such possibility?
--------------------------------


and the output is:

1 C
1 M
1 Q
1 Y
2 A
2 H
2 N
2 U
2 W
3 O
4 E
5 I
6 T
7 S

But i require the output as:

1 Y
1 Q
1 M
1 C
2 W
2 U
2 N
2 H
2 A
3 O
4 E
5 I
6 T
7 S

please provide me the solution?

hemanth.avs
Well, there are two things you can do:
1. Find the boundaries of each group in the sorted data set and reverse the group (for example, the boundaries of 2 would be 4 and 8 [well, 9]).
2. I believe you can pass your own comparison function to std::sort.
hi helios,

my vector is ::: vector<pair<int, char> > vect;


i am using sort :: sort(vect.begin(),vect.end(),myfunction);


my function is::

bool myfunction (pair<int,char> i,pair<int,char> j)
{

return ( (i.second < j.second) && (i.first < j.first) );
}

I have idea how to use function in case of normal datatypes. But i have no idea in case of pair.
plz provide me any info in case of pair.

hemanth.avs
thanks helios. it worked out in my case


bool myfunction (pair<int,char> i,pair<int,char> j)
{

return ( ( (i.first > j.first) && (i.second > j.second) ));
}



Your function does not match your initial requirements because it does not handle the
case where i.first == j.first.

As a matter of good practice, you should take the parameters by const reference instead of by value.
Also, you should implement the function in terms of operator< rather than operator>.

1
2
3
4
5
bool myfunction( const pair<int, char>& i, const pair<int, char>& j ) {
    if( i.first < j.first ) return false;
    if( j.first < i.first ) return true;
    return j.second < i.second;
}

Topic archived. No new replies allowed.