在C++中,std::set
是一個關聯容器,它包含一組唯一的對象
下面是如何在C++中使用std::set
的一些基本示例:
#include <iostream>
#include <set>
std::set
對象并插入元素:std::set<int> my_set;
my_set.insert(5);
my_set.insert(3);
my_set.insert(7);
my_set.insert(1);
注意,std::set
會自動刪除重復的元素。在這個例子中,數字1已經存在,所以它不會被插入。
auto it = my_set.find(3);
if (it != my_set.end()) {
std::cout << "Found: " << *it << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
std::set
:for (const auto& element : my_set) {
std::cout << element << " ";
}
std::cout << std::endl;
這將輸出:1 3 5 7
my_set.erase(3);
現在,my_set
包含1, 5, 7
。
if (my_set.count(5)) {
std::cout << "5 is in the set" << std::endl;
} else {
std::cout << "5 is not in the set" << std::endl;
}
這將輸出:5 is in the set
這只是std::set
的基本用法。您還可以使用其他成員函數(如size()
、clear()
等)來操作std::set
。要了解更多關于std::set
的信息,請參閱C++標準庫文檔。