Iterator on pointer to Object

Hi,
i'm coding on an exercise for class, and can't find an solution.

I've got a class Person

1
2
3
4
5
6
  class Person{
private:
    std::string name;
    int alter;
    float groesse;
    std::string geschlecht;


and a class wich stores pointers to those Objects in a vector.

1
2
3
class PersonenListe{
private:
    std::vector<Person*> p;


Now I set an iterator onto the first element of the vector p. And I want to access the string "geschlecht" via the iterator.

1
2
3
4
5
6
std::vector<Person*>::iterator it = p.begin();

if(it->geschlecht == 'M'){
            counter++;
            it++;
        }


But I can't get it to work. I don't even understand the error i get.

Error:
"PersonenListe.cpp:35:16: error: request for member 'geschlecht' in '* it.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-><Person**, std::vector<Person*> >()', which is of pointer type 'Person*' (maybe you meant to use '->' ?)"

Any Ideas?
Last edited on
try: if( (*(*it)).geschlecht == 'M' ) or if( (*it)->geschlecht == 'M' )
Last edited on
Why are you using a std::vector<Person*> instead of std::vector<Person>?

It would be helpful if you would post the smallest possible complete program that illustrates your problem.
OK, this already helped me i got the solution.

I had to write a function to return the string "geschlecht" since its private. Also I had to use "" instead of '' since its a string and not a char.

if( (*(*it)).getSex()== "M" ) works perfectly.

Thank you very much!
But why the vector<Person*> ?

Normally in C++ you try to avoid pointers as much as possible.


It's part of the exercise.
std::vector<Person*> was on the exercise sheet itself.
Topic archived. No new replies allowed.