Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data out of the STL's const_iterator?

Tags:

c++

iterator

stl

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()

like image 874
alexgolec Avatar asked Feb 26 '10 23:02

alexgolec


People also ask

How to access data of iterator in c++?

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.

What is the difference between iterator and const_iterator?

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).

Why do we need const iterator?

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.


2 Answers

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.

like image 94
Tyler McHenry Avatar answered Nov 02 '22 18:11

Tyler McHenry


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) ...
like image 3
sth Avatar answered Nov 02 '22 19:11

sth