C++ set 的使用
生活随笔
收集整理的這篇文章主要介紹了
C++ set 的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
set 的介紹
C++ 中set 類模板又稱為集合類模板,它的主要特點就是元素會自動排序切不允許有重復的元素
不允許直接修改元素值,不提供直接存取元素的任何操作函數,set 同樣也是STL中的模板使用的時候
需要先引入#include?<set>
對上面的內容寫一個demo證實下
#include <iostream>
#include <string>
using namespace std;
#include <set>int main()
{// 創建一個空的setset<int> a;a.insert(1);a.insert(5);a.insert(2);a.insert(3);a.insert(4);a.insert(2); // 這個set 無法插入cout << a.size() << endl; // 不允許重復,打印結果為 5 //使用迭代器遍歷元素set<int>::iterator it;for (it = a.begin(); it != a.end(); it++){cout << *it << endl; // 自動排序,打印結果為12345}
}
set方法說明
| 函數 | 說明 |
| begin | set中第一個元素的引用 |
| end | set中最后一個元素的引用 |
| size | 返回set的個數 |
| empty | 判斷集合是否為空,為空返回true |
| find(x) | 返回一個指向x的迭代器,如果x不存在,則返回的迭代器等于end |
| upper_bound(x) | 返回一個指向x的迭代器 |
| lower_bound(x) | 返回一個迭代器指向位于x之前切緊鄰x |
| clear | 清空集合元素 |
| rbegin | 返回一個反向迭代器,指向向量末尾元素之后 |
| rend | 返回一個反向迭代器,指向向量起始元素 |
| erase(i) | 刪除第i位置的元素(注意不能直接為數組,需要用begin或者end) |
| erase(start,end) | 刪除指定的元素返回,注意是前包含后不包含,里面不能是數字 |
| insert(i,x) | 把 i 插入到x位置 |
| insert(i,x,y) | 把 i 插入到x到y 的位置 |
| swap | 交換2個集合的內容 |
demo 練習
#include <iostream>
#include <string>
using namespace std;
#include <set>int main()
{// 聲明一個setset<char> iset;// 獲取默認set的sizecout << iset.size() << endl;// 插入元素iset.insert('A');iset.insert('B');iset.insert('C');iset.insert('D');// 獲取set的sizecout << iset.size() << endl;//使用迭代器遍歷元素set<char>::iterator it;for (it = iset.begin(); it != iset.end(); it++){cout << *it << endl;}// find查找it = iset.find('D');if (it == iset.end()){cout << "未找到" << endl;}else{cout << "找到了" << endl;}// set判空if (iset.empty()){cout << "set為空" << endl;}else{cout << "set不為空" << endl;}// 清空setiset.clear();return 0;
}
總結
以上是生活随笔為你收集整理的C++ set 的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++ list 的使用
- 下一篇: qq个性签名隐藏