sort data

i am having problems sorting data...i dont know to to go about it here is my code that i dont knw how to sort

<code>
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int i;
struct person
{
string name;
int age;
};
person NAME[10];
for(i=0;i<10;i++)
{
cout <<"list of players and their ages";
cout <<"Enter the name and age of the person"<<endl;
cout <<"Name:";
cin >>NAME[i].name;
cout <<"Age:";
cin >> NAME[i].age;
}
for(i=0;i<10;i++)
{
cout <<NAME[i].name<<"::"<<NAME[i].age<<"years"<<endl;
}
return 0;
}
</code>

i want to sort it out so that it can output names and ages in ascending order.
Please use [code] tags. Also, don't name variables in all caps.

person people[10];


To sort the people, you must provide a comparison function.

1
2
3
4
5
6
7
8
9
bool person_compare_names( const person& lhs, const person& rhs )
{
  return lhs.name < rhs.name;
}

bool person_compare_ages( const person& lhs, const person& rhs )
{
  return lhs.age < rhs.age;
}

Now it is as easy as:

 
#include <algorithm> 
1
2
3
4
5
// sort by name
sort( people, people + number_of_people, person_compare_names  );

// sort by age
sort( people, people + number_of_people, person_compare_ages );

If you would like to see something like:

John, 27
Mary, 27
Anne, 22
Fred, 21
Lucy, 21
Zeke, 21
Doug, 19

...then you need to do a two-pass stable sort.

1
2
3
4
// First, sort by name
sort( people, people + number_of_people, person_compare_names );
// Next, stable sort by age
stable_sort( people, people + number_of_people, person_compare_ages );

Hope this helps.
tanx
Topic archived. No new replies allowed.