Qt容器(QVector,QList)::end()返回一个无法引用的迭代器
Qt container (QVector, QList) ::end() return an iterator which cannot be referred
[情况]
这种情况发生在QVector
和QList
上,这里我用后者作为例子。
测试代码:
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);
}
相关文章:
- 返回一个引用C++中另一个类对象的对象的有效方法
- 返回一个C++引用变量 VS 返回一个变量
- 有没有办法重写一个返回指向 istringstream 的指针的函数,而不是返回一个引用?
- 如何使用只有一个引用参数的可变长度参数列表
- 为什么重载 ostream 的运算符<<需要一个引用"&"?
- C++ const-cast 一个引用
- 嵌套绑定到成员,需要一个指针,得到了一个引用.做什么
- r-Rcpp可以公开一个引用同一类的C++类方法
- 有没有办法获取对 MFC 对话框中所有子窗口或控件的引用,因为我有一个引用该控件的 CWnd 对象
- C++一个引用的多个转发:首先复制,然后移动
- 在C++中,我是否可以声明一个引用,以表明没有任何内容会修改它
- 将一个对象传递给一个引用函数,即面试测试
- 需要解释才能理解一个引用的例子
- 一个好的C++编译器会优化一个引用吗
- 我有一个引用,想调用一个需要 boost::shared_ptr 的函数
- 在C++中有一个引用成员有什么问题?
- *return如何隐式返回一个引用
- 为什么我得到一个未对齐指针的警告,而不是一个引用
- 是否可以在不同位置为一个引用分配不同的值
- 编写一个引用类型的函数,用作l值来处理它的r值