阅读量:124
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 class="hljs-keyword">else {
std::cout << "3 is not in the set." << std>
- 删除元素:
my_set.erase(3);
- 遍历
set中的元素:
for (const auto& element : my_set) {
std::cout << element class="hljs-string">" ";
}
std::cout << std>
- 获取
set的大小和容量:
std::cout << "Size of the set: " << my class="hljs-built_in">size() << std class="hljs-string">"Capacity of the set: " << my class="hljs-built_in">capacity() << std>
- 清空
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 class="hljs-built_in">size() << std class="hljs-keyword">for (const auto& element : my_set) {
std::cout << element class="hljs-string">" ";
}
std::cout << std class="hljs-keyword">if (my_set.find(3) != my_set.end()) {
std::cout << "3 is in the set." << std class="hljs-keyword">else {
std::cout << "3 is not in the set." << std class="hljs-built_in">erase(3);
if (my_set.find(3) != my_set.end()) {
std::cout << "3 is in the set." << std class="hljs-keyword">else {
std::cout << "3 is not in the set." << std class="hljs-keyword">return 0;
}
输出结果:
Size of the set: 4
1 5 7 3
Size of the set: 3
1 5 7