How can I use stable_sort function with structure?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Master
Learning poster
Posts: 82
Joined: Thu Oct 10, 2002 1:15 pm
Location: St. Johns, Canada
Contact:

How can I use stable_sort function with structure?

Post by Master »

I cannot able to use the STL function stable_sort for sorting an array of structure. Could any one pls tell me how can I use it?

Thanks in advance
M H Rasel
CUET Old Sailor.
Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Post by Dominik Michniewski »

if I remember using sort functions with STL is involwed with writting class with special compare function ... look at i.e. MSDN library to check it ... but I don't know how it's in ANSI ....

Best regards
DM
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)
shamim
A great helper
Posts: 498
Joined: Mon Dec 30, 2002 10:10 am
Location: Bozeman, Montana, USA

Post by shamim »

Here is an example:

[cpp]


struct type
{
int age,gpa;

};
// defining comp
bool comp( const type &a, const type &b)
{
if ( a.age < b.age)
return true;
if ( a.age > b.age )
return false;
if ( a.gpa<b.gpa)
return true;

return false;
}

int main()
{
type a[20];
// take input
sort( a, a+10, comp) ;

}

[/cpp]

The above will sort the first ten elements first by checking age and if that is equal then by gpa.
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba »

I think that the following solution is better:
[cpp]struct type{
int age,gpa;
bool operator<(const type& t){
return (age == t.age) ? (gpa < t.gpa) : (age < t.age);
}
};[/cpp]
and then:
[cpp]sort(a,a+10);[/cpp]
and when you want to do it in reverse order:
[cpp]sort(a,a+10,greater<type>());[/cpp]
(in that case, don't forget to include <functional>).
Master
Learning poster
Posts: 82
Joined: Thu Oct 10, 2002 1:15 pm
Location: St. Johns, Canada
Contact:

Post by Master »

Thanks a lot :lol:

M H Rasel
CUET Old Sailor
Post Reply

Return to “C++”