I have something that runs like this:
T baseline;
list<T>::const_iterator it = mylist.begin();
while (it != mylist.end()) {
if (it == baseline) /* <----- This is what I want to make happen */
// do stuff
}
My problem is that I have no idea how to extract the data from the iterator. I feel like this is a stupid thing to be confused about, but I have no idea how to do it.
EDIT : Fixed begin.end()
you can use something=*it to access an element pointed by the iterator. The *it==baseline is a correct code for that kind of behaviour.
A const iterator points to an element of constant type which means the element which is being pointed to by a const_iterator can't be modified. Though we can still update the iterator (i.e., the iterator can be incremented or decremented but the element it points to can not be changed).
Const iterators are slightly faster, and can improve code readability. The default QList::const_iterator constructor creates an uninitialized iterator. You must initialize it using a QList function like QList::constBegin(), QList::constEnd(), or QList::insert() before you can start iterating.
Iterators have an interface that "looks" like a pointer (but they are not necessarily pointers, so don't take this metaphor too far).
An iterator represents a reference to a single piece of data in a container. What you want is to access the contents of the container at the position designated by the iterator. You can access the contents at position it
using *it
. Similarly, you can call methods on the contents at position it
(if the contents are an object) using it->method()
.
This doesn't really relate to your question, but it is a common mistake to be on the lookout for (even I still make it from time to time): If the contents at position it
are a pointer to an object, to call methods on the object, the syntax is (*it)->method()
, since there are two levels of indirection.
The syntax to use an iterator is basically the same as with a pointer. To get the value the iterator "points to" you can use dereferencing with *
:
if (*it == baseline) ...
If the list is a list of objects you can also access methods and properties of the objects with ->
:
if (it->someValue == baseline) ...
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