Error in inserting and reading files from a person vector

Viewed 42

I created a person class with instance variables name and age. Then I created a person vector to store persons. I wrote two functions to insert and print the persons in the vector. But I get an error message:

error: no matching function for call to 'std::vector<person*>::push_back(person&)'
             arr.push_back(p1);

Below is my code.

vector<person*> arr;

void addPersons(person p1) {
        arr.push_back(p1);
    }

void printPerson () {
 //creating iterator
    vector<person*>::iterator it;

    //printing all elements
    cout << "vector arr elements are: ";
    for (it = arr.begin(); it != arr.end(); it++)
        cout << *it << " ";
    cout << endl;

}

The main function

int main() {
    person p1("okoro", 12);

    p1.printPerson();

    return 0;

}
1 Answers

If the vector can have the ownership of the persons (in the sense of the memory), just use

vector<person> arr;

As suggested in the comments.

Then your iteration becomes (using c++11 loops):

for (const person& p : arr)
    cout << p << " ";

By the way, it is a good convention to Capitalize the first letter of types: Person

Related