Fork me on GitHub

STL——容器(Set & multiset)的大小

1. set.size();  //返回容器中元素的数目

2. set.empty();//判断容器是否为空

empty() 是由一下代码实现的,可以发现,当长度为0时返回 false,以此判断容器为空

1     _NODISCARD bool empty() const noexcept 
2     {
3         return size() == 0;
4     }

 注意事项: 与 vector、deque 的连续存储不同,set 是拥有红黑树实现的,他没有 resize() 方法

 

代码例子:

 1 #include <iostream>
 2 #include <set>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     set<int> setInt;
 9 
10     if (setInt.empty())
11     {
12         cout << "容器中元素数量为:" << setInt.size() << endl;
13         cout << "容器为空" << endl;
14     }
15     else
16     {
17         cout << "容器不为空" << endl;
18         cout << "容器中元素数量为:" << setInt.size() << endl;
19         cout << "遍历setInt:";
20         for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
21         {
22             cout << *it << " ";
23         }
24     }
25 
26     //在容器中插入元素
27     cout << endl << "插入5个元素" << endl << endl;
28     setInt.insert(3);
29     setInt.insert(9);
30     setInt.insert(7);
31     setInt.insert(5);
32     setInt.insert(1);
33     
34     if (setInt.empty())
35     {
36         cout << "容器为空" << endl;
37         cout << "容器中元素数量为:" << setInt.size() << endl;
38     }
39     else
40     {
41         cout << "容器不为空" << endl;
42         cout << "容器中元素数量为:" << setInt.size() << endl;
43         cout << "遍历setInt:";
44         for (set<int>::iterator it = setInt.begin(); it != setInt.end(); it++)
45         {
46             cout << *it << " ";
47         }
48     }
49 
50     cout << endl;
51     return 0;
52 }

打印结果:

 

 

 

 

 

 

 

 

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

posted @ 2020-06-08 01:01  索智源  阅读(308)  评论(0编辑  收藏  举报