一、簡介
集合(Set)是一種包含已排序對象的關聯容器,不允許有重復元素。
二、完整程序代碼
/*請務必運行以下程序后對照閱讀*/ #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容器不提供下標操作符 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容器只是單純的鍵的集合。當我們想知道某位用戶是否存在時,使用set容器是最合適的。
參考網址:http://www.cplusplus.com/reference/set/set/
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答
圖片精選