STL——遍历 删除 set 元素

==================================声明==================================

本文版权归作者所有。

本文原创,转载必须在正文中显要地注明作者和出处,并保证文章(包括本声明)的完整性。

未经作者授权请勿修改(包括本声明),保留法律追究的权利。

未经作者授权请勿用于学术性引用。

未经作者授权请勿用于商业出版、商业印刷、商业引用以及其他商业用途。

本文不定期修正完善,为保证内容正确,建议移步原文处阅读。

本文链接:http://www.cnblogs.com/wlsandwho/p/4468023.html

=======================================================================

STL是个好东西,在客户端上用一用没什么问题。

在使用multimap时,伴随一个set来统计multimap中key的种类。真是省心省力。

然而,时间换空间、空间换时间。伴随set会带来开销。

世间安得双全法?那必定是晦涩难懂的,不能在普罗大众间流传。

=======================================================================

以前一直没怎么注意遍历删除set。当我随手写了个小代码后,我想知道人类是怎么做的。

于是搜一搜。

不知为何,网上真是转载文章一大抄,这也罢了,可为何STL遍历删除的例子都要列上错误做法?

=======================================================================

set的erase并不返回iterator,所以在遍历删除的时候,要使用

void erase (iterator position);

函数。

一个不错的小网站http://www.cplusplus.com/reference/

=======================================================================

贴上我的纯手工小代码。

 1 #include <iostream>
 2 #include <set>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     set<int> setIntTest;
 9     set<int>::iterator itsetIntTest;
10 
11     setIntTest.insert(1);
12     setIntTest.insert(2);
13     setIntTest.insert(3);
14     setIntTest.insert(4);
15     setIntTest.insert(5);
16     setIntTest.insert(6);
17     setIntTest.insert(7);
18 
19     wcout<<L"Before:"<<endl;
20     for (itsetIntTest=setIntTest.begin();itsetIntTest!=setIntTest.end();itsetIntTest++)
21     {
22         wcout<<*itsetIntTest<<endl;
23     }
24 
25     //////////////////////////////////////////////////////////////////////////
26     wcout<<L"Remove those can not be divided by 3:"<<endl;
27     for (itsetIntTest=setIntTest.begin();itsetIntTest!=setIntTest.end();)
28     {
29         if ((*itsetIntTest)%3!=0)
30         {
31             wcout<<L"Remove	"<<*itsetIntTest<<endl;
32 
33             setIntTest.erase(itsetIntTest++);//必然是擦除后再移动迭代器,所以后++            
34         }
35         else
36         {
37             itsetIntTest++;//这个就无所谓前后了,没有涉及增删操作。
38         }
39     }
40 
41     //////////////////////////////////////////////////////////////////////////
42     wcout<<L"After:"<<endl;
43     for (itsetIntTest=setIntTest.begin();itsetIntTest!=setIntTest.end();itsetIntTest++)
44     {
45         wcout<<*itsetIntTest<<endl;
46     }
47 
48     return 0;
49 }
原文地址:https://www.cnblogs.com/wlsandwho/p/4468023.html