在C++項目中,std::set
是一個關聯容器,它包含了一組唯一的元素,并且這些元素會自動按鍵值進行排序
<set>
頭文件。#include <set>
std::set
對象。std::set<int> mySet; // 創建一個空的整數集合
insert()
函數向std::set
中添加元素。mySet.insert(5);
mySet.insert(10);
mySet.insert(1);
std::set
中的元素已經按鍵值排序,可以使用迭代器遍歷元素。for (auto it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
erase()
函數刪除指定元素或范圍內的元素。mySet.erase(5); // 刪除元素5
find()
函數查找指定元素。if (mySet.find(10) != mySet.end()) {
std::cout << "Element 10 found"<< std::endl;
} else {
std::cout << "Element 10 not found"<< std::endl;
}
std::set
中元素的數量。std::cout << "Size of the set: " << mySet.size()<< std::endl;
empty()
函數判斷std::set
是否為空。if (mySet.empty()) {
std::cout << "The set is empty"<< std::endl;
} else {
std::cout << "The set is not empty"<< std::endl;
}
clear()
函數清空std::set
中的所有元素。mySet.clear();
通過以上方法,可以在C++項目中高效地使用std::set
函數。注意,std::set
中的元素是唯一的,重復插入相同元素不會增加元素數量。