I am having trouble adding objects to a list.
I want to make a List of Persons, and I know the size of the list is fixed at 5 people. Each Person has an age (int) and a gender (string). I want to add the Persons to the List, but I don't know how, I've only worked with integers now that I think of it.
Below is what I have so far. The random age and gender is working, however clunky that is. I'm thinking instead of creating the Persons as I did, maybe somehow I should create them dynamically in a for loop which will somehow generate the age and gender per loop iteration? Maybe the list should be pointers to the Person objects.
#include <iostream>
#include <list>
#include <memory>
using namespace std;
class Person {
private:
const int OLDEST_AGE = 100;
const int YOUNGEST_AGE = 1;
int age;
string gender;
public:
Person()
{
age = generateAge();
gender = generateGender();
}
// Person: generate random age for Person, from 1-100
int generateAge() {
int randomAge;
randomAge = rand() % (OLDEST_AGE - YOUNGEST_AGE + 1) + YOUNGEST_AGE;
return randomAge;
};
// Person: generate random gender for Person, Male or Female
string generateGender() {
int genderNumber;
genderNumber = rand() % (1 - 0 + 1) + 0;
if (genderNumber == 1)
return "Male";
else
return "Female";
};
void getStats() {
cout << "Person Age: " << age << endl;
cout << "Person Gender: " << gender << endl;
};
};
int main()
{
Person P1, P2, P3, P4, P5;
// Just to see if the objects are created
P1.getStats();
P2.getStats();
P3.getStats();
P4.getStats();
P5.getStats();
list<Person> myList;
list<Person>::iterator IT;
for (int i = 1; i <= 5; i++)
//don't know how to add each Person to the list
myList.push_back(P1);
cout << "myList contains: ";
for (IT = myList.begin(); IT != myList.end(); IT++)
// similar to above, how do I get the list to print each object's stats
P1.getStats();
cout << endl;
return 0;
}