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

被刻印的时光 ゝ 提交于 2019-12-22 08:59:33

问题


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


回答1:


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.




回答2:


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



回答3:


Use:

if (*it == baseline) 



回答4:


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




回答5:


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;



回答6:


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/



来源:https://stackoverflow.com/questions/2345581/how-to-get-data-out-of-the-stls-const-iterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!