File tree 2 files changed +141
-0
lines changed
2 files changed +141
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < set>
3
+ using namespace std ;
4
+
5
+ // set基本概念
6
+ /*
7
+
8
+ 简介:
9
+ 所有元素都会在插入时自动排序
10
+ 本质:
11
+ set/mutiset 属于关联式容器,底层结构是用二叉树实现
12
+
13
+ set与 multiset 区别:
14
+ - set 不允许容器中有重复的元素
15
+ - multiset 允许容器中有重复的元素
16
+
17
+ */
18
+
19
+ // set构造与赋值
20
+ /*
21
+
22
+ 构造:
23
+ - set<T> st; // 默认构造函数
24
+ - set(const set &st); // 拷贝构造函数
25
+
26
+ 赋值:
27
+ - set& operator= (const set &st); // 重载等号操作符
28
+
29
+ */
30
+
31
+ void printSet (const set<int > &s)
32
+ {
33
+ for (set<int >::const_iterator it = s.begin (); it != s.end (); it++)
34
+ {
35
+ cout << *it << " " ;
36
+ }
37
+ cout << endl;
38
+ }
39
+
40
+ void test01 ()
41
+ {
42
+ set<int > s1;
43
+ // 插入数据只有 insert 方式
44
+ s1.insert (10 );
45
+ s1.insert (20 );
46
+ s1.insert (10 );
47
+ s1.insert (10 );
48
+ s1.insert (40 );
49
+ s1.insert (30 );
50
+
51
+ // 遍历容器
52
+ printSet (s1);
53
+ // set容器特点:所有元素插入时自动排序,不允许插入重复值
54
+
55
+ // 拷贝构造
56
+ set<int > s2 (s1);
57
+ printSet (s2);
58
+
59
+ // 赋值
60
+ set<int > s3;
61
+ s3 = s2;
62
+ printSet (s3);
63
+ }
64
+
65
+ int main ()
66
+ {
67
+ test01 ();
68
+ return 0 ;
69
+ }
Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < set>
3
+ using namespace std ;
4
+
5
+ // set 大小与交换
6
+ /*
7
+ - size(); // 返回容器中元素的数目
8
+ - empty(); // 判断容器是否为空
9
+ - swap(st); // 交换两个集合容器
10
+ */
11
+
12
+ void printSet (const set<int > &s)
13
+ {
14
+ for (set<int >::const_iterator it = s.begin (); it != s.end (); it++)
15
+ {
16
+ cout << *it << " " ;
17
+ }
18
+ cout << endl;
19
+ }
20
+
21
+ // 大小
22
+ void test01 ()
23
+ {
24
+ set<int > s1;
25
+ s1.insert (10 );
26
+ s1.insert (20 );
27
+ s1.insert (30 );
28
+ s1.insert (40 );
29
+
30
+ // 判断是否为空
31
+ if (s1.empty ())
32
+ {
33
+ cout << " s1 为空" << endl;
34
+ }
35
+ else
36
+ {
37
+ cout << " s1 不为空" << endl;
38
+ cout << " s1 大小为 " << s1.size () << endl;
39
+ }
40
+ }
41
+
42
+ // 交换
43
+ void test02 ()
44
+ {
45
+ set<int > s1;
46
+ s1.insert (10 );
47
+ s1.insert (20 );
48
+ s1.insert (30 );
49
+ s1.insert (40 );
50
+
51
+ set<int > s2;
52
+ s2.insert (100 );
53
+ s2.insert (200 );
54
+ s2.insert (300 );
55
+ s2.insert (400 );
56
+
57
+ cout << " 交换前:" << endl;
58
+ printSet (s1);
59
+ printSet (s2);
60
+
61
+ s1.swap (s2);
62
+ cout << " 交换后:" << endl;
63
+ printSet (s1);
64
+ printSet (s2);
65
+ }
66
+
67
+ int main ()
68
+ {
69
+ test01 ();
70
+ test02 ();
71
+ return 0 ;
72
+ }
You can’t perform that action at this time.
0 commit comments