c++ STL庫容器之集合set代碼實例
set 簡介
set是STL中一種標(biāo)準(zhǔn)關(guān)聯(lián)容器,其鍵值就是實值,實值就是鍵值,不可以有重復(fù),所以我們不能通過set的迭代器來改變set的元素的值。它底層使用平衡的搜索樹——紅黑樹實現(xiàn),插入刪除操作時僅僅需要指針操作節(jié)點即可完成,不涉及到內(nèi)存移動和拷貝,所以效率比較高。set,顧名思義是“集合”的意思,在set中元素都是唯一的,而且默認(rèn)情況下會對元素自動進(jìn)行升序排列,支持集合的交(set_intersection),差(set_difference) 并(set_union),對稱差(set_symmetric_difference) 等一些集合上的操作,如果需要集合中的元素允許重復(fù)那么可以使用multiset。
set 初始化
set<int> seta;
cout << "初始化前set的大?。? << seta.size() << endl;
cout << "初始化前set是否為空: " << seta.empty() << endl;
//初始化set
//用insert函數(shù)初始化
for(int i = 0; i < 10; i++)
{
seta.insert(i);
}
/*
//這里也可以使用數(shù)組來賦值進(jìn)行初始化
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
set<int> seta(a,a+10);
*/
cout << "初始化后set的大?。? << seta.size() << endl;
cout << "初始化后set是否為空: " << seta.empty() << endl;
set 基本操作
set.begin() 返回set容器的第一個元素
set.end() 返回set容器的最后一個元素
set.clear() 刪除set容器中的所有的元素
set.empty() 判斷set容器是否為空
set.insert() 插入一個元素
set.erase() 刪除一個元素
set.size() 返回當(dāng)前set容器中的元素個數(shù)
這里我們介紹幾個函數(shù)
1. find
查找一個元素,如果容器中不存在該元素,返回值等于seta.end()
//使用find時要與end()進(jìn)行比較
//測試find函數(shù)
if(seta.find(0) == seta.end())
{
cout << "0不存在" << endl;
}else{cout << "0存在" << endl;}
if(seta.find(11) != seta.end())
{
cout << "11存在" << endl;
}else{cout << "11不存在" << endl;}
2. erase
seta.erase() 刪除一個元素 seta.clear() 刪除set容器中的所有的元素
//測試erase函數(shù) seta.erase(9); cout << "刪除9之后seta的值: " << endl; print(seta);
3. insert
//測試插入函數(shù)insert
int a[5] = {11, 12, 13, 14, 15};
seta.insert(a,a+5);
cout << "插入后seta的值: " << endl;
print(seta);
一個簡單的介紹set的小程序
#include <iostream>
#include <set>
using namespace std;
//抽象一個函數(shù),用來輸出集合set中的值
void print(set<int> seta)
{
set<int >::iterator itor = seta.begin();
while(itor != seta.end())
{
cout << "set內(nèi)的值為:" << *itor << endl;
itor++;
}
}
int main()
{
set<int> seta;
cout << "初始化前set的大?。? << seta.size() << endl;
cout << "初始化前set是否為空: " << seta.empty() << endl;
//初始化set
//用insert函數(shù)初始化
for(int i = 0; i < 10; i++)
{
seta.insert(i);
}
/*
//這里也可以使用數(shù)組來賦值進(jìn)行初始化
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
set<int> seta(a,a+10);
*/
cout << "初始化后set的大?。? << seta.size() << endl;
cout << "初始化后set是否為空: " << seta.empty() << endl;
print(seta);
//測試find函數(shù)
if(seta.find(0) == seta.end())
{
cout << "0不存在" << endl;
}else{cout << "0存在" << endl;}
if(seta.find(11) != seta.end())
{
cout << "11存在" << endl;
}else{cout << "11不存在" << endl;}
//測試erase函數(shù)
seta.erase(9);
cout << "刪除9之后seta的值: " << endl;
print(seta);
//測試插入函數(shù)insert
int a[5] = {11, 12, 13, 14, 15};
seta.insert(a,a+5);
cout << "插入后seta的值: " << endl;
print(seta);
return 0;
}
運行結(jié)果

到此這篇關(guān)于c++ STL庫容器之集合set代碼實例的文章就介紹到這了,更多相關(guān)c++ STL庫容器之集合set內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入學(xué)習(xí)C語言中的函數(shù)指針和左右法則

