c++ set容器
时间: 2023-08-06 18:25:17 浏览: 54
C++中的set是一个关联容器,它可以存储一组不重复的元素,并且按照一定的顺序进行排序。set容器中的元素默认是按照升序排列的,也可以自定义排序规则。set容器的底层实现是使用红黑树来实现的,因此其插入、删除、查找等操作的时间复杂度均为O(logn)。
在使用set容器时,需要包含头文件<set>,并使用set模板类定义一个set对象。例如:
```c++
#include <set>
using namespace std;
set<int> mySet;
```
以上代码定义了一个存储整型数据的set容器对象mySet。接下来就可以通过调用set容器的成员函数来对mySet进行操作了。
相关问题
c++ set容器用法
以下是关于C++ set容器的用法示例:
1. 判断set是否为空并检查元素是否在set中
```cpp
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> myset;
for (int i = 1; i < 11; i++) {
myset.insert(i);
}
if (!myset.empty()) {
cout << "set is not empty" << endl;
}
if (myset.count(3)) {
cout << "3 is in the set" << endl;
}
myset.clear();
return 0;
}
```
2. 创建set容器
```cpp
#include <iostream>
#include <set>
#include <vector>
using namespace std;
int main() {
set<int> myset;
int a[5] = {1, 2, 3, 4, 5};
vector<int> vec{1, 2, 3, 4, 5};
set<int> myset1(a, a + 5); // 根据数组地址初始化
set<int> myset2(vec.begin(), vec.end()); // vector地址初始化
set<int> myset3(myset2.begin(), myset2.end()); // set初始化
set<int> myset4(myset3); // 复制初始化
return 0;
}
```
c++ set容器基本操作
C++ STL库中的set容器是一个用于存储元素的关联容器,它的元素默认按照升序排列,并且保证元素的唯一性。set容器的基本操作包括:
1. 插入元素:使用insert()函数向set容器中插入元素。插入元素的时间复杂度为O(log n)。
```c++
#include <iostream>
#include <set>
int main() {
std::set<int> s;
s.insert(3);
s.insert(1);
s.insert(4);
s.insert(1); // 重复元素不会被插入
s.insert(5);
for (auto x : s) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
```
上述代码输出:1 3 4 5
2. 删除元素:使用erase()函数删除set容器中的元素,可以指定要删除的元素值,也可以指定一个迭代器范围。删除元素的时间复杂度为O(log n)。
```c++
#include <iostream>
#include <set>
int main() {
std::set<int> s{3, 1, 4, 1, 5};
s.erase(1); // 删除元素值为1的元素
for (auto x : s) {
std::cout << x << " ";
}
std::cout << std::endl;
return 0;
}
```
上述代码输出:3 4 5
3. 查找元素:使用find()函数和count()函数查找set容器中的元素,find()函数返回一个指向要查找的元素的迭代器,如果元素不存在,则返回end()迭代器。count()函数返回要查找的元素在set容器中出现的次数,因为set容器中的元素保证唯一性,所以count()函数的返回值只能是0或1。查找元素的时间复杂度为O(log n)。
```c++
#include <iostream>
#include <set>
int main() {
std::set<int> s{3, 1, 4, 1, 5};
auto it = s.find(4);
if (it != s.end()) {
std::cout << "4 is found" << std::endl;
} else {
std::cout << "4 is not found" << std::endl;
}
std::cout << "1 appears " << s.count(1) << " times" << std::endl;
std::cout << "2 appears " << s.count(2) << " times" << std::endl;
return 0;
}
```
上述代码输出:4 is found,1 appears 1 times,2 appears 0 times。
除了上述基本操作外,set容器还支持迭代器操作和比较操作。更详细的使用方法可以参考C++ STL库的set容器文档。