Qt容器(QVector,QList)::end()返回一个无法引用的迭代器

Qt container (QVector, QList) ::end() return an iterator which cannot be referred

本文关键字:一个 引用 迭代器 end QVector 容器 QList 返回 Qt      更新时间:2023-10-16

[情况]

这种情况发生在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++转换有关吗?

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

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

QList::end()

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

QList::last()

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

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

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

您只需要考虑end元素不是一个有效的元素。你可以使用之类的东西浏览整个列表

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