tags:

views:

98

answers:

6

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

+8  A: 

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.

Tyler McHenry
+2  A: 

Use:

if (*it == baseline) 
dirkgently
+3  A: 

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) ...
sth
+1  A: 

Use *it to access the element pointed by the iterator. When you are comparing i guess you should use if (*it == baseline)

Amal
+1  A: 

the std iterators overload the operator*(), this way you can access the referenced location the same way as if it was a pointer.

T const& a = *it;
josefx
A: 

from what i know std iterators are not pointers, but are a thin wrapper around the actual pointers to the underlying individual data elements.

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.

Also if you are dealing with collections from STL you can consider using functions such as find_if http://www.cplusplus.com/reference/algorithm/find_if/