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.
How can I use stable_sort function with structure?
Moderator: Board moderators
-
- Guru
- Posts: 834
- Joined: Wed May 29, 2002 4:11 pm
- Location: Wroclaw, Poland
- Contact:
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
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)
Born from ashes - restarting counter of problems (800+ solved problems)
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.
[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.
-
- Guru
- Posts: 584
- Joined: Thu Jun 19, 2003 3:48 am
- Location: Sanok, Poland
- Contact:
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>).
[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>).