我有vector<list<customClass> >
我有一个迭代器vector<list<customClass> >::const_iterator x
当我尝试访问customClass的成员时,如下所示:
x[0]->somefunc()
,我收到非指针类型的错误/未找到。
答案 0 :(得分:4)
迭代器取消引用列表。如果要访问该列表中的对象,则必须使用list方法来执行此操作。但是,由于stl列表不会使索引运算符重载,因此这不是一个有效的选项。
这将允许您在列表中的第一个元素上调用somefunc:
(*x).front().somefunc();
另一方面,如果你想要一个列表的迭代器,你可以这样做:
list<customClass>::const_iterator listIterator = (*x).begin();
listIterator->somefunc();
答案 1 :(得分:4)
这是一个完整的工作片段。要回答你的问题,注释[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 []
}
答案 2 :(得分:2)
iterator类不提供operator []因此你不能像那样使用它。你应该将它用作x-&gt; somefunc()
答案 3 :(得分:2)
x是一个迭代器,它的作用就像一个指针 - 它指向一个列表。因此,您只能使用std :: list。
成员的函数答案 4 :(得分:2)
const迭代器将取消引用list<customClass>
对象而不是指向该列表的指针。您必须访问该列表中的索引...
忽略错误检查:
(*x)[0].somefunc()
答案 5 :(得分:0)
如果你想直接访问list和vector类已经实现了[]运算符,那么只需直接访问它:vectorObj [x] .someFunc();
迭代器用于遍历列表(按名称建议迭代),使用它。