Using Iterators in a Pointer List

I am trying to use an iterator over listpointers:

int main () {
    list<Game*> Games;
    Games = build_list_from_file(); //Reading the games.info file
    list<Game*>::iterator it = Games.begin();
    it++;
    cout << *it->get_name() << endl ;
    //  ...
}

When I compile it, I have this error:

error: request for member ‘get_name’ in ‘* it.std::_List_iterator<_Tp>::operator-><Game*>()’, which is of pointer type ‘Game*’ (maybe you meant to use ‘->’ ?)
  cout << *it->get_name() << endl ;
               ^

Gameis a class that has a member function get_namethat returns the name of the game. What to do to make this compilation?

+4
source share
4 answers

You have a problem with operator precedence , try adding parentheses

(*it)->get_name()
+8
source

You are facing an operator priority issue . ->has a higher priority than *, so you really do:

*(it->get_name())

, Game* - , get_name. , :

(*it)->get_name()
+7

You must write (*it)->get_name()because it operator->has a higher priority than the dereference operator.

+6
source

This is all about operator priority.

It should be (*it)->get_name()

If you can use C ++ 11, use auto for better readability.

int main (){
    list<Game*> Games;
    Games = build_list_from_file(); //Reading the games.info file
    auto it = Games.begin();
    it++;
    cout << (*it)->get_name() << endl ;
//  ...
}
+2
source

All Articles