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