【问题标题】:c++ iterator confusionc++迭代器混淆
【发布时间】:2009-12-12 04:00:53
【问题描述】:

我有一个vector<list<customClass> >

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

当我尝试像这样访问 customClass 的成员时:

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

【问题讨论】:

  • 也在寻找一个实际的解决方案:)

标签: c++ stl iterator


【解决方案1】:

这是一个完整的工作 sn-p。为了回答您的问题,带有注释 [1] 的行显示了如何取消引用 const_iterator,而注释 [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】:

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

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

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

    另一方面,如果您想要列表的迭代器,您可以执行以下操作:

    list<customClass>::const_iterator listIterator = (*x).begin();
    listIterator->somefunc();
    

    【讨论】:

      【解决方案3】:

      iterator 类不提供 operator[] 因此你不能那样使用它。您应该将其用作 x->somefunc()

      【讨论】:

      • 但这并不指向实际的课程。有没有办法不指向列表而是指向类
      • 为此,您必须使用两个间接级别。从第一个迭代器中获取列表对象。然后将迭代器获取到列表对象中,取消引用该迭代器以获取某个类对象
      • 因为 x 是向量的迭代器,所以它是一个随机访问迭代器。因此,它提供了 operator[]。然而,结果是不提供“->”的 std::list 的 const 左值。
      【解决方案4】:

      x 是一个迭代器,它的作用类似于一个指针——它指向一个列表。所以你只能使用 std::list 的成员函数。

      【讨论】:

        【解决方案5】:

        const 迭代器将取消对 list&lt;customClass&gt; 对象的引用,而不是指向该列表的指针。您必须访问该类列表中的索引...

        忽略错误检查:

        (*x)[0].somefunc()
        

        【讨论】:

        • stl 列表不会重载索引运算符
        【解决方案6】:

        如果你想直接访问列表,向量类已经实现了[]操作符,那么直接访问即可:vectorObj[x].someFunc();

        iterator 用于遍历列表(如名称所示迭代它),使用它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-21
          • 1970-01-01
          • 2013-09-07
          • 1970-01-01
          • 1970-01-01
          • 2014-03-05
          • 1970-01-01
          • 2013-03-24
          相关资源
          最近更新 更多