iterator with vector pointer

26,195

Solution 1

The iterator needs to be the same type as the container:

vector<Person>::iterator it;

should be:

vector<Person*>::iterator it;

Solution 2

 vector<Person*> *personVec = new vector<Person*>();

this is a pointer to a vector of person pointers

vector<Person>::iterator it;
for(it = personVec->begin() ; it != personVec->end() ; ++it)
{
    cout << it->getName() << endl;
}

your iter is declare incorrectly you need an iter to a vector of person pointers

you have an iter to a vector of person s

vector<Person*>::iterator it;
for(it = personVec->begin() ; it != personVec->end() ; ++it)
{
    cout << (*it)->getName() << endl;
}

http://www.cplusplus.com/reference/std/iterator/

and

http://www.cplusplus.com/reference/stl/vector/begin/

Share:
26,195
Lefsler
Author by

Lefsler

Updated on May 12, 2020

Comments

  • Lefsler
    Lefsler about 4 years

    I created a vector of pointers

    vector<Person*> *personVec = new vector<Person*>();
    

    Person contains:

    getName();
    getAge();
    

    If I try to use the iterator it doesn't work.. Here is how I use it:

        vector<Person>::iterator it;
        for(it = personVec->begin() ;
            it != personVec->end() ;
            ++it)
        {
            cout << it->getName() << endl;
        }
    

    I tried vector<Person*>::iterator it; but no luck with that either.

    Thanks.

    • ildjarn
      ildjarn about 12 years
      You can't get a vector<Person>::iterator from a vector<Person*>...
  • Matthew Iselin
    Matthew Iselin about 12 years
    +1, also the it->getName() should become (*it)->getName().