Search code examples
c++for-loopc++11linked-listiterator

How to iterate through a list of pointers to an object?


I have a typedef statement:

typedef list <Event *> EventList;

which is on its own in my header file (not part of a class).

I have a function nd_to_el(), where I want to iterate through this EventList, which has already been filled with instances of Event.

This is what I tried:

EventList::iterator it;

for (it = this->el.begin(); it != this->el.end(); ++it){
    cout << (*it)->key << endl;
}

(I am also not sure if dereferencing the iterator is correct here or not)

but I get this error:

error: request for member ‘end’ in ‘((CS302_Midi*)this)->CS302_Midi::el’, which is of pointer type ‘EventList*’ {aka ‘std::__cxx11::list<Event*>*’} (maybe you meant to use ‘->’ ?)
for (it = this->el.begin(); it != this->el.end(); ++it)

I don't think using the arrow operator is what I intend here.


Solution

  • According to the error message

    {aka ‘std::__cxx11::list<Event*>*’} (maybe you meant to use ‘->’ ?)

    it seems you have a pointer to a list.

    In this case the loop can look like

    for (it = this->el->begin(); it != this->el->end(); ++it){
        cout << (*it)->key << endl;
    }
    

    Or you could use a range-based for loop like

    for ( const auto &e : *this->el )
    {
        cout << e->key << endl;
    }