C++ set
时间: 2023-07-03 09:05:27 浏览: 50
C++中的set是一种关联容器,它存储唯一且有序的元素。在set中插入的元素会自动按照升序排序,并且每个元素都是唯一的。set常用的操作包括插入、删除、查找、迭代器遍历等。
以下是set的一些常用函数:
1. insert():向set中插入元素。
2. erase():从set中删除指定元素。
3. find():在set中查找指定元素。
4. size():返回set中元素的个数。
5. empty():判断set是否为空。
6. begin() 和 end():返回set的起始迭代器和结束迭代器,可以用于遍历set中的元素。
以下是set的示例代码:
```c++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> s;
// 向set中插入元素
s.insert(3);
s.insert(1);
s.insert(5);
s.insert(4);
// 遍历set中的元素
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
cout << endl;
// 查找set中的元素
if (s.find(5) != s.end())
cout << "5 is in the set" << endl;
// 删除set中的元素
s.erase(3);
// 判断set是否为空
if (!s.empty())
cout << "set size: " << s.size() << endl;
return 0;
}
```
输出结果:
```
1 3 4 5
5 is in the set
set size: 3
```