如何从STL的const_iterator中获取数据? [英] How to get data out of the STL's const_iterator?
问题描述
我有这样的东西:
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.
固定了begin.end()
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).
迭代器表示对容器中单个数据的引用.您想要的是在迭代器指定的位置访问容器的内容.您可以使用*it
访问位置it
的内容.同样,您可以使用it->method()
在位置it
上的内容上调用方法(如果内容是对象).
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()
.
这与您的问题并没有真正的联系,但是要提防这是一个常见的错误(即使我仍然时不时地这样做):如果位置it
上的内容是指向对象的指针,以调用该对象上的方法,语法为(*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.
这篇关于如何从STL的const_iterator中获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!