[英]c++ iterator confusion
我有一个vector<list<customClass> >
我有一个迭代器vector<list<customClass> >::const_iterator x
当我尝试访问customClass的成员时,如下所示:
x[0]->somefunc()
,我得到非指针类型的错误/未找到。
迭代器取消引用列表。 如果要访问该列表中的对象,则必须使用list方法来执行此操作。 但是,由于stl列表不会使索引运算符重载,因此这不是有效选项。
这将允许您在列表中的第一个元素上调用somefunc:
(*x).front().somefunc();
另一方面,如果你想要一个列表的迭代器,你可以这样做:
list<customClass>::const_iterator listIterator = (*x).begin();
listIterator->somefunc();
这是一个完整的工作片段。 要回答你的问题,注释[1]的行显示如何取消引用const_iterator,而注释[2]显示如何使用operator []取消引用。
#include <vector>
#include <list>
#include <iostream>
class Foo
{
public:
void hello() const
{
std::cout << "hello - type any key to continue\n";
getchar();
}
void func( std::vector<std::list<Foo> > const& vec )
{
std::vector<std::list<Foo> >::const_iterator qVec = vec.begin();
qVec->front().hello(); // [1] dereference const_iterator
}
};
int main(int argc, char* argv[])
{
std::list<Foo> list;
Foo foo;
list.push_front(foo);
std::vector<std::list<Foo> > vec;
vec.push_back(list);
foo.func( vec );
vec[0].front().hello(); // [2] dereference vector using []
}
迭代器类不提供operator []因此你不能像那样使用它。 你应该用它作为x-> somefunc()
x是一个迭代器,它的作用就像一个指针 - 它指向一个列表。 所以你只能使用std :: list成员的函数。
const迭代器将取消引用list<customClass>
对象而不是指向该列表的指针。 您必须访问该列表中的索引...
忽略错误检查:
(*x)[0].somefunc()
如果你想直接访问list和vector类已经实现了[]运算符,那么只需直接访问它:vectorObj [x] .someFunc();
迭代器用于遍历列表(如名称所示迭代它),使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.