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