Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL: list with Pointers - Iterator cannot access?

Tags:

c++

list

stl

I am struggeling with an STL list that holds Pointers of my "Object" object.

I declared:

list<Object*> objectlist;

and inserted via:

this->objectlist.push_back(new Object(address,value,profit));

and tried to iterate like in maps and others:

list<Object*>::iterator iter;

iter = this->objectlist.begin();

while(iter != this->objectlist.end())
{
    iter->print();
}

Where print() is a public Method of class Object;

Whats wrong here?

I cannot access via iterator to the objects in the list ?

like image 789
Stefan Avatar asked Jun 23 '11 12:06

Stefan


People also ask

What is iterator in STL?

An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.

What is iterator in CPP?

An iterator is an object that can iterate over elements in a C++ Standard Library container and provide access to individual elements.

Why are iterators useful?

The use of iterators bring you closer to container independence. You're not making assumptions about random-access ability or fast size() operation, only that the container has iterator capabilities. You could enhance your code further by using standard algorithms.


3 Answers

You need (*iter)->print();

Since you have an iterator to a pointer, you have to first de-reference the iterator (which gets you the Object*) then the arrow de-references the Object * and allows the call to print.

like image 130
RC. Avatar answered Sep 19 '22 15:09

RC.


You are not incrementing your iterator! Change your while loop to a for loop like so:

for (list<Object*>::const_iterator iter = this->objectlist.begin(),
     end = this->objectlist.end();
     iter != end;
     ++iter)
{
    (*iter)->print();
}

(Also iter dereferences to a pointer, like the other answers have pointed out.)

like image 41
Kerrek SB Avatar answered Sep 23 '22 15:09

Kerrek SB


You can access the value pointed by iterator with *iter

Also, remember to increment the iterator in each iteration. Otherwise you get stuck in an endless loop.

Like this:

iter = this->objectlist.begin();

while(iter != this->objectlist.end())
{
    (*iter)->print();
    iter++;
}
like image 32
Juho Avatar answered Sep 23 '22 15:09

Juho