本文链接:
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>
4 using namespace std;
6 int main()
8 set<int> setIntTest;
9 set<int>::iterator itsetIntTest;
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);
19 wcout<<L"Before:"<<endl;
20 for (itsetIntTest=setIntTest.begin();itsetIntTest!=setIntTest.end();itsetIntTest++)
22 wcout<<*itsetIntTest<<endl;
25 //////////////////////////////////////////////////////////////////////////
26 wcout<<L"Remove those can not be divided by 3:"<<endl;
27 for (itsetIntTest=setIntTest.begin();itsetIntTest!=setIntTest.end();)
29 if ((*itsetIntTest)%3!=0)
31 wcout<<L"Remove\t"<<*itsetIntTest<<endl;
33 setIntTest.erase(itsetIntTest++);//必然是擦除后再移动迭代器,所以后++
35 else
37 itsetIntTest++;//这个就无所谓前后了,没有涉及增删操作。
41 //////////////////////////////////////////////////////////////////////////
42 wcout<<L"After:"<<endl;
43 for (itsetIntTest=setIntTest.begin();itsetIntTest!=setIntTest.end();itsetIntTest++)
45 wcout<<*itsetIntTest<<endl;
48 return 0;