Problem Creating Vector of Objects

Am trying to create a vector of objects, called Person that consists of a name and an age. Both the name and age are inputed from the user and are being stored in local variables n and a.

n is declared string and a is declared int.

In main

declared vector as

vector< Person> people;

In Person class

public:

// constructor
Person(string, int )

sets and gets for name and age

private:
int age;
string name;

also have set and get functions.

How do i assign the name and age to the vector.

I was using people.push_back(string n, int a) but does not accept it.

Unable to see how to create this as an object of vectors only double, int etc.

Am I missing a step?






Use YourVector.push_back( Person( SomeString, SomeInt ) ); instead.
Last edited on
The vector holds Person objects, not strings and integers.

1
2
3
4
5
Person a("Nick", 4);
Person b("Nicle", 10);

people.push_back(a);
people.push_back(b);

or do exactly what Vlad said.

1
2
people.push_back(Person("Nick", 4));
people.push_back(Person("Nicle", 10));
Last edited on
I updated the pushback to the following:

people.push_back(Person(n,a));

this is currently in main after my while loop which is promting the user for information.

My first question is should the push_back statement be in the loop with the input.

The second thing I was trying to do was create a function that read the vector and increased the age by 1.

This is the function I created:

void Person::incrementAge(vector<Person> & person)
{
for (int i = 0; i < person.size(); i++)
{
cout << person[i];
person[];
}
}


I wanted to display each element of the vector and increase the age by one, should that be done in the setAge instead or can it be done in this function?




As this function is a member of the class it has access to all members of the class including private members. So it will be simpler to write

++person[i].age;
I also have a vector that points to the name object

vector<Car>cars;

// constructor

Car( string, Person, Person);

void setModel(string m);
void setDriver(Person *d);
void setOwner(Person *d);

private:
Person *driver;
Person *owner;
string model;


};

Car::Car( string m, Person*, Person*)
{

model = m;

}

string Car::getModel()
{
return model;
}

Person Car::getDriver()
{
return *driver;
}


Person Car::getOwner()
{
return *owner;
}

cars.push_back(Car(m,*d,*o));

Not sure what I am doing wrong
Topic archived. No new replies allowed.