Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Iterators on a list of pointers

I am trying to iterator over a list of pointers:

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 ;
               ^

Game is a class that has the get_name member function, which returns the name of the game. What should I do to make this compile?

like image 775
Ali Bahrami Avatar asked Nov 28 '22 14:11

Ali Bahrami


2 Answers

You have an issue with operator precedence, try adding parentheses

(*it)->get_name()
like image 152
Cory Kramer Avatar answered Dec 05 '22 16:12

Cory Kramer


You've run into an operator precedence issue. -> has higher precedence than *, so you're really doing:

*(it->get_name())

which doesn't compile since Game* doesn't have any members, much less get_name. You need to do the dereference first, which needs to be parenthesized:

(*it)->get_name()
like image 21
Barry Avatar answered Dec 05 '22 16:12

Barry