Page 1 of 1
How can I use stable_sort function with structure?
Posted: Tue Jan 27, 2004 6:19 am
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.
Posted: Tue Jan 27, 2004 9:45 am
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
Posted: Tue Jan 27, 2004 2:23 pm
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.
Posted: Thu Jan 29, 2004 2:07 am
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>).
Posted: Sun Feb 08, 2004 11:28 am
by Master
Thanks a lot
M H Rasel
CUET Old Sailor