C++ 的 set
容器是一种关联式容器,它包含一组唯一的对象。每个元素在插入时都会自动按键进行排序。set
容器通常使用红黑树实现,因此插入、删除和查找操作的时间复杂度都是 O(log n)。
以下是使用 C++ set
容器的基本步骤:
#include <iostream>
#include <set>
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 <iostream>
#include <set>
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