QList<QString> list; list << "A" << "B" << "C" << "D"; QListIterator<QString> i(list); while (i.hasNext()) qDebug() << i.next();
Unlike STL-style iterators (covered below), Java-style iterators point between items rather than directly at items
Then we call hasNext() to check whether there is an item after the iterator. If there is, we callnext() to jump over that item. The next() function returns the item that it jumps over。
java迭代器指向item中间位置,next跳过item,并返回跳过的item。
The remove() function removes the last item that we jumped over from the list. The call to remove() does not invalidate the iterator, so it is safe to continue using it.
remove移除跳过的元素。迭代器不会失效。
c++这边:
在循环遍历一个容器时,需要根据条件删除其中的某个元素,如何处理iterator?答案是:对于序列式容器标准写法是这样:
//vector<int> con;
for(vector<int>::iterator iter=con.begin();
iter!=con.end();)
{
if((*iter) == 99)
iter=con.erase(iter);
else
++iter;
}
对于关联容器是这样:
//map<int,int> con;
for(map<int,int>::iterator iter=con.begin();
iter!=con.end();)
{
if(iter->second == 99)
con.erase(iter++);
else
++iter;
}
本文详细介绍了C++容器中迭代器的使用方法,包括STL风格与Java风格的迭代器的区别,以及如何在循环遍历容器时进行元素删除的操作。
586

被折叠的 条评论
为什么被折叠?



