一、在vector和list容器中使用迭代器来间隔的删除表中的中对象。
我们用到迭代器中erase操作符来进行删除操作。iterator erase(iterator pos)删除迭代器所给位置的对象,这对于list双向链表是常时间操作,而对于vector来说则不是。这操作返回值是调用之前pos所指向的元素的下一个位置。所以这个操作使pos失效,pos不再有用,因为它所指向的容器对象已经被删除了。
#include<iostream>
#include <iterator>
#include <list>
#include <vector>
using namespace std;
template <typename container>
void remove_every_other_item(container &lst)
{
typename container::iterator itr = lst.begin();
while (itr != lst.end())
{
itr = lst.erase(itr);
if (itr != lst.end())
{
itr++;
}
}
}
int main( )
{
list<int> itr(800000,1);
list<int>::iterator it;
remove_every_other_item(itr);
for(list<int>::iterator it = itr.begin(); it!= itr.end(); it++)
{
cout<<*it<< ' ';
}
return 0;
}

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



