开发者

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

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 h开发者_开发技巧ave 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()


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


Use:

if (*it == baseline) 


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


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;


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜