STL库set
发表于:2024-12-21 | 分类: C++
字数统计: 476 | 阅读时长: 2分钟 | 阅读量:

set

构造

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <set>

using namespace std;

int main()
{
// 初始化空 set
set<int> s1;

// 使用初始化列表
set<int> s2 = {1, 2, 2, 3}; // 允许重复, 但不会插入重复元素(自动去重)

// 使用拷贝构造函数
set<int> s3(s2);

// 使用范围构造函数
set<int> s4(s2.begin(), s2.end());

return 0;
}

api

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <set>

using namespace std;

int main()
{
// 初始化列表
set<int> s = {1, 2, 3};

// 插入元素
s.insert(4);
s.insert(5);

// 查看容量
cout << "当前容量: " << s.size() << endl;

// 查找元素
auto it = s.find(3);
if (it != s.end())
{
cout << "元素 3 存在,值为" << *it << endl;
}
else
{
cout << "元素 3 不存在" << endl;
}

// 判断元素是否存在
if (s.count(2))
{
cout << "元素 2 存在" << endl;
}

// 删除元素,传入元素值
s.erase(2);
cout << "删除元素 2 后容量: " << s.size() << endl;

// 清空集合
s.clear();
cout << "清空后容量: " << s.size() << endl;

return 0;
}

遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <set>

using namespace std;

int main()
{
set<int> s = {1, 2, 3, 4, 5};

// 使用范围 for 遍历 (C++11)
for (auto &item : s)
{
cout << item << " ";
}
cout << endl;

// 使用迭代器遍历
for (auto it = s.begin(); it != s.end(); ++it)
{
cout << *it << " ";
}
cout << endl;

return 0;
}

并发修改

还是迭代器失效,参考vector,下方是正确方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <set>

using namespace std;

int main()
{
set<int> s = {1, 2, 3, 4, 5};

// 使用迭代器遍历
for (auto it = s.begin(); it != s.end();)
{
if (*it == 3)
{
it = s.erase(it); // 注意返回
}
else
{
++it;
}
}
cout << endl;

return 0;
}

底层

红黑树

上一篇:
STL容器的有序性与重复性
下一篇:
STL库map