【问题标题】:Qt container (QVector, QList) ::end() return an iterator which cannot be referred [duplicate]Qt容器(QVector,QList)::end()返回一个无法引用的迭代器[重复]
【发布时间】:2023-04-01 00:13:01
【问题描述】:

[情况]

QVectorQList 都会出现这种情况,这里我以后者为例。

测试代码:

QList<int> test;    
for (int i=0; i<10; i++)
    test.append(i);

// First
qDebug()<<"[First]";
qDebug()<<"Directly return:"<<test.first();
QList<int>::iterator itr_first = test.begin();
qDebug()<<"By iterator:"<<*itr_first;

// Last
qDebug()<<"[Last]";
qDebug()<<"Directly return:"<<test.last();
QList<int>::iterator itr_last = test.end();
qDebug()<<"By iterator:"<<*itr_last; //<--- ***No value can be referred from here***

itr_last = itr_last-1;
qDebug()<<"By iterator(modified):"<<*itr_last;

输出为:

[第一个]

直接返回:0

按迭代器:0

[最后一个]

直接返回:9

通过迭代器:-842150451

通过迭代器(修改):9

[问题]

QList::begin() 返回第一项的迭代器不同,我不明白为什么 QList::end() 返回无法引用的不可用迭代器。这对我来说很烦人,有时会让我的程序出错。

这是什么原因?和 C++ 对流有什么关系吗?

【问题讨论】:

  • 请阅读半开范围和结束迭代器,beginend 背后的概念是 C++ 的基础(以及编程中的任何东西)。
  • 谢谢,我有点缺乏这个背景。
  • @KubaOber 我是 OP,我认为它也是重复的。我自己删除有关系吗?
  • 是的,但以后先检查是否有重复项。删除许多已回答问题的用户将因浪费大家的时间而被暂停。

标签: c++ qt


【解决方案1】:

QList::end() 返回的迭代器(就像 STL 容器中的所有 end 迭代器一样)不引用列表的元素 - 它严格用作标记标记。取消引用它永远无效。

来自 Qt 文档 (http://qt-project.org/doc/qt-4.8/qlist.html):

QList::end()

返回一个 STL 样式的迭代器,指向列表中最后一项之后的虚构项。

QList::last()

返回对列表中最后一项的引用。列表不能为空。如果列表可以为空,请在调用此函数之前调用 isEmpty()。

【讨论】:

  • 谢谢,虽然我期待一些讨论like this
【解决方案2】:

如果您在此处阅读文档:iterator QList::end ()

你可以看到:Returns an STL-style iterator pointing to the imaginary item after the last item in the list.

您只需要考虑结束元素不是有效元素。您可以使用类似的东西遍历列表

for(int i = 0; i < list.size(); i++)
{
    qDebug() << list.at(i);
}

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    相关资源
    最近更新 更多