how to sort arr in struct

Aug 9, 2011 at 3:41pm
i have
struct mido
{
int wage,boss;
};
arr[0].wage=5 , arr[0].boss=0
arr[1].wage=2 , arr[1].boss=2
arr[2].wage=4 , arr[2].boss=1
arr[3].wage=3 , arr[3].boss=0
arr[4].wage=2 , arr[4].boss=2
i want to sort arr[].boss at same time each parallel value from arr[].wage go with to be
arr[0].wage=5 , arr[0].boss=0
arr[1].wage=3 , arr[1].boss=0
arr[2].wage=4 , arr[2].boss=1
arr[3].wage=2 , arr[3].boss=2
arr[4].wage=2 , arr[4].boss=2

how can i do this ???? or can i do it with sort function in algorithm.h??
Aug 9, 2011 at 5:13pm
You can do it really easily with the sort() function, but you probably would want to implement some sort of custom comparison (see the examples on this website here: http://cplusplus.com/reference/algorithm/sort/ regarding how to do this).

Best of luck! And... by the way, it's just <algorithm>.

-Albatross
Last edited on Aug 9, 2011 at 5:15pm
Aug 9, 2011 at 6:09pm
plz give me code on sorting it becz the link doesn't have code on sorting an array struct
Aug 9, 2011 at 6:22pm
Okay, I'll give you a hint.

std::sort(array,array+length);

Best of luck!

-Albatross
Aug 9, 2011 at 8:12pm
if you want use STL and write a general code you need define first your operator < or > for sortin like :
1
2
3
4
5
6
7
8
9
10
11
bool operator <(const mido &l, const mido &r)
{
      return l.boss < r.boss;
}

//then you can use sort STL like :

sort(arr, arr + sizeof(arr) / sizeof(arr[0]));

if you work with array in stl some time may be take warning so you must use 
checked_array_iterator in namespace of stdext and header file iterator


in this algorithm arr is array of contain "mido"
Last edited on Aug 9, 2011 at 8:13pm
Topic archived. No new replies allowed.