- #include <iostream>
- #include <iterator>
- #include <list>
- using namespace std;
- int main(int argc, char **argv)
- {
- list<int> nlist;
- list<int>::iterator it;
- for (int i = 0; i < 10; ++i)
- nlist.push_back(i);
- for (it = nlist.begin(); it != nlist.end();) {
- if (*it % 2 == 0)
- it = nlist.erase(it);
- else
- ++it;
- }
- copy(nlist.begin(), nlist.end(), ostream_iterator<int>(cout, "\n"));
- return 0;
- }
- // 上面是前增高效率用法,因为后增会创建临时变量。
- // 网上有这样两种用法
-
一:
for(;test_list_it != test_list.end();)
{
test_list.erase(test_list_it++);
} or
二 :
-
for(;test_list_it != test_list.end();)
{
std::list<int>::iterator iter_e=test_list_it++;
test_list.erase(iter_e);
} -
可以看出其实,这二者都是删除临时迭代器指向的元素,而当前的迭代器已经指定到下一个元素。
-
其实 it = nlist.erase(it); 本身就返回一个list删除后,迭代器指向的元素。
-
-
所以,就用返回值赋予当前迭代器 指针,该指针继续遍历list。
- #include <iostream>
C++ STL list erase()用法。
最新推荐文章于 2022-02-13 20:51:59 发布