STL——容器(Set & multiset)的删除 erase
2024-09-08 05:54:52
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 }
打印结果:
==================================================================================================================================
最新文章
- json的理解及读取
- ThinkPhp 3.2 ajax无刷新分页(未完全改完,临时凑合着用)
- spring AOP 实现事务和主从读写分离
- 几条复杂的SQL语句
- Codeforces Round #271 (Div. 2)
- Bzoj 3831 [Poi2014]Little Bird
- [Design Pattern] Observer Pattern 简单案例
- 利用jQuery打造个性网站
- AssetBundle实现服务器下载并从本地读取
- Java中的this关键字
- python 内存NoSQL数据库
- Ping监控脚本
- 什么是cookie?cookie的使用(设置,读取,删除)
- jenkins 设置钉钉通知--钉钉机器人
- 1071 Speech Patterns
- R语言中将数据框(data.frame)中字符型数据转化为数值型
- 要生成在[min,max]之间的随机整数,
- 阿里VS华为-开源镜像站体验及评测
- 使用jquery处理数据时要注意的问题
- Android开发:《Gradle Recipes for Android》阅读笔记(翻译)4.5——使用Android Libraries