【问题标题】:Why I'm printing value out of range?为什么我打印的值超出范围?
【发布时间】:2016-04-04 17:13:20
【问题描述】:

考虑这段代码:

class Foo123
{
    QList<int> a = (QList<int>()) << 1 << 2 << 3;
    QList<int>::const_iterator it;

public:

    Foo123()
    {
        it = a.begin();
    }

    void print()
    {
        qDebug() << *it;
        while(move())
        {
            qDebug() << *it;
        }
    }


    bool move()
    {
        if(it != a.end())
        {
            ++it;
            return true;
        }

        return false;
    }
};

    Foo123 f;
    f.print();

我总是在打印结束时得到一个额外的数字,就像这样:

1
2
3
58713 // this is random, from what I can tell

我想我正在打印一个范围值,但我不明白如何。谁能指出我的错误?

【问题讨论】:

  • 你在增加迭代器之前检查它。您基本上将a.end() 打印为最后一个值。
  • a.end() 不指向最后一个元素,而是一个“过去的”迭代器,不应该被取消引用,这可能会造成混淆。
  • @vu1p3n0x:我想我错过了 a.end() 没有指向最后一个元素...

标签: qt c++11 listiterator


【解决方案1】:

这是因为你必须先递增,然后测试:

bool move()
    {
        ++it;
        if(it != a.end()) {
            return true;
        }

        return false;
    }

【讨论】:

    【解决方案2】:

    请注意,在 C++11 中,您可以使用初始化器列表来初始化列表(原文如此),您也可以就地初始化迭代器。

    所以,整件事,固定的,将是:

    #include <QtCore>
    
    class Foo123
    {
       QList<int> a { 1, 2, 3 };
       QList<int>::const_iterator it { a.begin() };
    public:
       void print()
       {
          qDebug() << *it;
          while (move()) qDebug() << *it;
       }
       bool move()
       {
          ++ it;
          return (it != a.end());
       }
    };
    
    int main() {
       Foo123 f;
       f.print();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-16
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多