代码之家  ›  专栏  ›  技术社区  ›  stan

C++迭代器混淆

  •  2
  • stan  · 技术社区  · 15 年前

    我有一个 vector<list<customClass> >

    我有一个迭代器 vector<list<customClass> >::const_iterator x

    当我试图这样访问CustomClass的成员时:

    x[0]->somefunc() ,我得到非指针类型的错误/未找到。

    6 回复  |  直到 15 年前
        1
  •  4
  •   Phillip Ngan    15 年前

    这是一个完整的工作片段。要回答您的问题,注释[1]所在的行显示了如何取消引用const迭代器,而注释[2]显示了如何使用运算符[]取消引用。

    #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
  •  4
  •   csj    15 年前

    迭代器取消对列表的引用。如果要访问该列表中的对象,则必须使用List方法进行访问。但是,由于STL列表不会重载索引运算符,因此这不是一个有效的选项。

    这将允许您在列表中的第一个元素上调用somefunc:

    (*x).front().somefunc();
    

    另一方面,如果需要列表的迭代器,可以这样做:

    list<customClass>::const_iterator listIterator = (*x).begin();
    listIterator->somefunc();
    
        3
  •  2
  •   Naveen    15 年前

    迭代器类不提供运算符[],因此不能这样使用它。您应该将其用作x->somefunc()。

        4
  •  2
  •   Mark Ransom    15 年前

    x是一个迭代器,它就像一个指针,指向一个列表。所以您只能使用std::list成员的函数。

        5
  •  2
  •   John Weldon user3678248    15 年前

    常量迭代器将取消引用 list<customClass> 对象不是指向该列表的指针。你必须访问该类列表中的索引…

    忽略错误检查:

    (*x)[0].somefunc()
    
        6
  •  0
  •   sap    15 年前

    如果要直接访问,则列表和向量类已经实现了[]运算符,因此只需直接访问它:vectorobj[x].somefunc();

    迭代器用于遍历列表(按照名称的建议进行迭代),为此使用它。