C++ STL入門教程(6) set(集合)的使用方法
一、簡(jiǎn)介
集合(Set)是一種包含已排序?qū)ο蟮年P(guān)聯(lián)容器,不允許有重復(fù)元素。
二、完整程序代碼
/*請(qǐng)務(wù)必運(yùn)行以下程序后對(duì)照閱讀*/ #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(); }
三、補(bǔ)充
map容器是鍵-值對(duì)的集合,好比以人名為鍵的地址和電話號(hào)碼。相反地,set容器只是單純的鍵的集合。當(dāng)我們想知道某位用戶是否存在時(shí),使用set容器是最合適的。
參考網(wǎng)址:http://www.cplusplus.com/reference/set/set/
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C++實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)簡(jiǎn)單的計(jì)算器功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01Linux環(huán)境g++編譯GDAL動(dòng)態(tài)庫(kù)操作方法
下面小編就為大家?guī)?lái)一篇Linux環(huán)境g++編譯GDAL動(dòng)態(tài)庫(kù)操作方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-05-05IOS 開發(fā)UITextView回收或關(guān)閉鍵盤
這篇文章主要介紹了IOS 開發(fā)UITextView回收或關(guān)閉鍵盤的相關(guān)資料,需要的朋友可以參考下2017-06-06C++實(shí)現(xiàn)簡(jiǎn)單BP神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)簡(jiǎn)單BP神經(jīng)網(wǎng)絡(luò),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05C語(yǔ)言實(shí)現(xiàn)學(xué)籍管理系統(tǒng)課程設(shè)計(jì)
這篇文章主要為大家詳細(xì)介紹了C語(yǔ)言實(shí)現(xiàn)學(xué)籍管理系統(tǒng)課程設(shè)計(jì),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-07-07