Order By Age Program

Hello, I just started learning C++ and I have to make a program that says who is the oldest person from a list of persons. I made a class Pers where i defined the class destructor, name and age but I don't know how to compare the age of all the persons in the list. Can somebody give me some advice? The class i created looks like this:
1
2
3
4
5
6
7
8
9
10
11
 class Pers
{
public:
Pers(char *bname, int bage);
int age;
char name[200];
};
Pers::Pers(char *bname,int bage)
{ strcpy(Pers::name, bname);
Pers::age=bage;}
closed account (48T7M4Gy)
Create a list (array) of Pers objects in main.
Then compare their ages.
Rather than use char arrays I would suggest that you use std::string and then as a container of the Person instances you use a std::vector, then you can use the std::sort:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Person
{
public:
	Person(string name, int age)
		: m_name(name)
		, m_age(age)
	{

	}

	static bool Compare(Person& p1, Person& p2)
	{
		return p1.m_age < p2.m_age;
	}

private:
	int m_age;
	string m_name;
};

typedef vector<Person> People;

void Populate(People& people)
{
	people.push_back(Person("Matthew", 31));
	people.push_back(Person("Mark", 33));
	people.push_back(Person("Luke", 30));
	people.push_back(Person("John", 35));
}

int main()
{
	People people;
	Populate(people);
	sort(people.begin(), people.end(), Person::Compare);

	return 0;
}
Last edited on
closed account (48T7M4Gy)
Rather than use char arrays


Keep in mind that the word 'array' is not solely in the domain of C-style char arrays and vectors are not the sole domain of the rather wider range of C++ STL containers also capable of sorting!

http://www.cplusplus.com/reference/stl/
Topic archived. No new replies allowed.