迭代器失效及解决方案

 1 // set::begin/end
 2 #include <iostream>
 3 #include <set>
 4 
 5 int main ()
 6 {
 7     int myints[] = {75,23,55};
 8     std::set<int> myset (myints,myints+2);
 9 
10     std::cout << "myset contains:";
11     for (std::set<int>::iterator it=myset.begin(); it!=myset.end();)
12     {
13         std::cout << ' ' << *it;
14         myset.erase(it); // 此操作导致迭代器失效,产生bug
15     }
16 /*    for (std::set<int>::iterator it=myset.begin(); it!=myset.end();)
17     {
18         std::cout << ' ' << *it;
19         myset.erase(it);
20         it = myset.begin();// 解决方案一
21     }*/
22 /*    for (std::set<int>::iterator it=myset.begin(); it!=myset.end();)
23     {
24         std::set<int>::iterator next = it;
25         ++next;
26         std::cout << ' ' << *it;
27         myset.erase(it);
28         it = next;  // 解决方案2
29     }*/
30     std::cout << '\n';
31 
32     return 0;
33 }

 

posted @ 2013-06-28 16:06  joythink89  阅读(321)  评论(0编辑  收藏  举报