阅读量:2
C++ 的 set 容器是一种关联式容器,它包含一组唯一的对象。每个元素在插入时都会自动按键进行排序。set 容器通常使用红黑树实现,因此插入、删除和查找操作的时间复杂度都是 O(log n)。
以下是使用 C++ set 容器的基本步骤:
- 包含头文件:
#include
#include
- 创建一个
set对象:
std::set<int> my_set;
- 向
set中插入元素:
my_set.insert(5);
my_set.insert(3);
my_set.insert(7);
my_set.insert(1);
- 检查元素是否存在于
set中:
if (my_set.find(3) != my_set.end()) {
std::cout << "3 is in the set." << std::endl;
} else {
std::cout << "3 is not in the set." << std::endl;
}
- 删除元素:
my_set.erase(3);
- 遍历
set中的元素:
for (const auto& element : my_set) {
std::cout << element << " ";
}
std::cout << std::endl;
- 获取
set的大小和容量:
std::cout << "Size of the set: " << my_set.size() << std::endl;
std::cout << "Capacity of the set: " << my_set.capacity() << std::endl;
- 清空
set:
my_set.clear();
- 销毁
set对象:
当 set 对象离开其作用域时,它会自动被销毁。
以下是一个完整的示例程序:
#include
#include
int main() {
std::set<int> my_set;
my_set.insert(5);
my_set.insert(3);
my_set.insert(7);
my_set.insert(1);
std::cout << "Size of the set: " << my_set.size() << std::endl;
for (const auto& element : my_set) {
std::cout << element << " ";
}
std::cout << std::endl;
if (my_set.find(3) != my_set.end()) {
std::cout << "3 is in the set." << std::endl;
} else {
std::cout << "3 is not in the set." << std::endl;
}
my_set.erase(3);
if (my_set.find(3) != my_set.end()) {
std::cout << "3 is in the set." << std::endl;
} else {
std::cout << "3 is not in the set." << std::endl;
}
return 0;
}
输出结果:
Size of the set: 4
1 5 7 3
Size of the set: 3
1 5 7
以上就是关于“C++的set容器怎样使用”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm