C++ STL入門教程(6) set(集合)的使用方法
一、簡介
集合(Set)是一種包含已排序?qū)ο蟮年P(guān)聯(lián)容器,不允許有重復(fù)元素。

二、完整程序代碼
/*請務(wù)必運行以下程序后對照閱讀*/
#include <set>
#include <iostream>
using namespace std;
int main()
{
///1. 初始化
set<int> num;
set<int>::iterator iter;
cout << num.max_size() << endl;///set容納上限
cout << endl;
///2. 添加元素
for (int i = 0; i < 10; i++)
num.insert(i);
cout << num.size() << endl;
cout << endl;
///3. 遍歷
///不同于map,set容器不提供下標(biāo)操作符
for (iter = num.begin(); iter != num.end(); iter++)
cout << *iter << " " ;
cout << endl;
cout << endl;
///4. 查詢
iter = num.find(1);
if (iter != num.end())
cout << *iter << endl;
else
cout << -1 << endl;
iter = num.find(99);
if (iter != num.end())
cout << *iter << endl;
else
cout << -1 << endl;
cout << endl;
///5. 刪除
iter = num.find(1);
num.erase(iter);
cout << num.size() << endl;
for (iter = num.begin(); iter != num.end(); iter++)
cout << *iter << " " ;
cout << endl;
cout << endl;
///6. 判空與清空
if (!num.empty())
num.clear();
}
三、補充
map容器是鍵-值對的集合,好比以人名為鍵的地址和電話號碼。相反地,set容器只是單純的鍵的集合。當(dāng)我們想知道某位用戶是否存在時,使用set容器是最合適的。
參考網(wǎng)址:http://www.cplusplus.com/reference/set/set/
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Linux環(huán)境g++編譯GDAL動態(tài)庫操作方法
下面小編就為大家?guī)硪黄狶inux環(huán)境g++編譯GDAL動態(tài)庫操作方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
IOS 開發(fā)UITextView回收或關(guān)閉鍵盤
這篇文章主要介紹了IOS 開發(fā)UITextView回收或關(guān)閉鍵盤的相關(guān)資料,需要的朋友可以參考下2017-06-06
C++實現(xiàn)簡單BP神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家詳細介紹了C++實現(xiàn)簡單BP神經(jīng)網(wǎng)絡(luò),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-05-05
C語言實現(xiàn)學(xué)籍管理系統(tǒng)課程設(shè)計
這篇文章主要為大家詳細介紹了C語言實現(xiàn)學(xué)籍管理系統(tǒng)課程設(shè)計,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07

