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 ?
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.
An iterator is an object that can iterate over elements in a C++ Standard Library container and provide access to individual elements.
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.
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.
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.)
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With