#include <deque>
#include <iostream>
#include <algorithm>
#include <stdexcept>
using namespace std;
void print(int num)
{
cout << num << " ";
}
int main()
{
//1. 初始化
deque<int> v;
deque<int>::iterator iv;
v.assign(10, 2);//將10個(gè)值為2的元素賦到deque中
cout << v.size() << endl; //返回deque實(shí)際含有的元素?cái)?shù)量
cout << endl;
//2. 添加
v.push_front(666);
for (int i = 0; i < 10; i++)
v.push_back(i);
for_each(v.begin(), v.end(), print);//需要#include <algorithm>
cout << endl;
cout << v.size() << endl;
cout << endl;
//3. 插入及遍歷、逆遍歷
v.insert(v.begin() + 3, 99);
v.insert(v.end() - 3, 99);
for_each(v.begin(), v.end(), print);
cout << endl;
for_each(v.rbegin(), v.rend(), print);//在逆序迭代器上做++運(yùn)算將指向容器中的前一個(gè)元素
cout << endl;
//一般遍歷寫法
for(iv = v.begin(); iv != v.end(); ++iv)
cout << *iv << " ";
cout << endl;
cout << endl;
//4. 刪除
v.erase(v.begin() + 3);
for_each(v.begin(), v.end(), print);
cout << endl;
v.insert(v.begin() + 3, 99);//還原
v.erase(v.begin(), v.begin() + 3); //注意刪除了3個(gè)元素而不是4個(gè)
for_each(v.begin(), v.end(), print);
cout << endl;
v.pop_front();
v.pop_back();
for_each(v.begin(), v.end(), print);
cout << endl;
cout << endl;
//5. 查詢
cout << v.front() << endl;
cout << v.back() << endl;
//危險(xiǎn)的做法,但一般我們就像訪問數(shù)組那樣操作就行
//for (int i = 15; i < 25; i++)
//cout << "Element " << i << " is " << v[i] << endl;
//安全的做法
int i;
try
{
for (i = 15; i < 25; i++)
cout << "Element " << i << " is " << v.at(i) << endl;
}
catch (out_of_range err)//#include <stdexcept>
{
cout << "out_of_range at " << i << endl;
}
cout << endl;
//6. 清空
v.clear();
cout << v.size() << endl;//0
for_each(v.begin(), v.end(), print); //已經(jīng)clear,v.begin()==v.end(),不會(huì)有任何結(jié)果。
return 0;
}
```
C++ STL 練手(deque的使用)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- vector的使用 list的使用 deque的使用 set的使用 map的使用 multiset的使用 mult...
- vector的使用 list的使用 deque的使用 set的使用 map的使用 multiset的使用 mult...
- 野球場,是講規(guī)矩的。 野球場的人,都是有故事的。 1 在野球場子里,判斷力是真的很重要的一件事情。有時(shí)候你看著一個(gè)...
- 你還在覺得投資理財(cái)是件離你很要遙遠(yuǎn)的事情嗎?還覺得自己的錢太少還不夠格理財(cái)? 如果還這樣想,我只能無奈...