STL——容器(Set & multiset)的刪除 erase


set.clear();             //清除所有元素

set.erase(pos);     //刪除pos迭代器所指的元素,返回下一個元素的迭代器。

set.erase(beg,end);    //刪除區間[beg,end)的所有元素,返回下一個元素的迭代器。

set.erase(elem);     //刪除容器中值為elem的元素。

 

代碼例子:

 1 #include <iostream>
 2 #include <set>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     set<int> setInt;
 9 
10     cout << "第一次遍歷setInt,沒有任何元素:";
11     for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
12     {
13         cout << *it << " ";
14     }
15 
16     //在容器中插入元素
17     cout << endl << "插入20個元素" << endl << endl;
18     for (int i = 0; i < 20; i++)
19     {
20         setInt.insert(i);
21     }
22     cout << "插入20個元素后的第二次遍歷setInt" << endl;
23     for (set<int>::iterator it = setInt.begin();it!=setInt.end(); it++)
24     {
25         cout << *it << " ";
26     }
27     cout << endl;
28     
29     //刪除迭代器所指的元素,返回下一個元素的迭代器。
30     cout << "刪除迭代器所指的元素 5 " << endl;
31     for (set<int>::iterator it = setInt.begin(); it != setInt.end();)
32     {
33         if (*it == 5)
34         {
35             it = setInt.erase(it);        //由於會返回下一個元素的迭代器,相當於進行了it++的操作
36         }
37         else
38         {
39             it++;
40         }
41     }
42     cout << endl << "刪除迭代器所指的元素 5 后遍歷 setInt:" << endl;
43     for (set<int>::iterator it = setInt.begin();  it != setInt.end(); it++)
44     {
45         cout << *it << " ";
46     }
47     cout << endl;
48 
49     //刪除區間(beg,end)的所有元素,返回下一個元素的迭代器。
50     cout << endl << "刪除元素 15 之后的所有元素";
51     for (set<int>::iterator it = setInt.begin(); it != setInt.end();)
52     {
53         if (*it == 15)
54         {
55             //如果找到15,刪除15之后所有的元素,由於會返回下一個元素的迭代器,相當於進行了it++的操作
56             it = setInt.erase(it, setInt.end());
57         }
58         else
59         {
60             it++;
61         }
62     }
63     cout << endl << "刪除元素 15 之后的所有元素后遍歷 setInt:";
64     for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
65     {
66         cout << *it << " ";
67     }
68     cout << endl;
69 
70     // 刪除容器中值為elem的元素
71     cout << endl << "刪除元素 10";
72     setInt.erase(10);
73     cout << endl << "刪除元素 10 之后遍歷 setInt:";
74     for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
75     {
76         cout << *it << " ";
77     }
78     cout << endl;
79 
80     //清除所有元素
81     cout << endl << "刪除所有元素";
82     setInt.clear();    
83     cout << endl << "刪除所有元素之后遍歷 setInt:";
84     for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
85     {
86         cout << *it << " ";
87     }
88     cout << endl;
89 
90     return 0;
91 }

打印結果:

 

 

 

 

 

 

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM