C++STL之雙端隊列容器

來源:互聯網
上載者:User

標籤:一個   隊列   管理   覆蓋   pretty   ras   code   processor   reverse   

C++STL之雙端隊列容器

 

deque雙端隊列容器與vector很類似,採用線性表順序儲存結構。但與vector區別,deque採用分塊的線性儲存結構來儲存資料,每塊的大小一般為512B,將之稱為deque塊,所有的deque塊使用一個map塊進行管理,每個map資料項目記錄各個deque塊的首地址,這樣的話,deque塊在頭部和尾部都可以插入和刪除。而不需要移動任何元素,而不需要移動其他元素(使用push_back()方法在尾部插入元素,會擴張隊列,而使用push_front()方法在首部插入元素和使用insert()方法在中間插入元素,只是將原位置上的元素進行覆蓋,不會增加新元素)一般來說,當考慮到容器元素的記憶體配置策略和操作的效能時deque相當於vector更有優勢。

*建立deque對象 
與vector類似

*插入元素 
使用push_back()方法從尾部插入元素,會不斷擴張隊列。

#include<iostream>#include<deque>using namespace std; int main() {    deque<int> d;    d.push_back(1);    d.push_back(2);    cout<<d[0]<<" : "<<d[1]<<endl;    return 0; }

 

從頭部插入元素,不會增加新元素,只將原來有的元素覆蓋。

 #include<iostream> #include<deque> using namespace std; int main() {    deque<int> d;    d.push_back(1);    d.push_back(2);    d.push_back(3);    d.push_front(10);//d.insert(d.begin()+1, 10);    d.push_front(20);//d.insert(d.begin()+2, 20);    cout<<d[0]<<" "<<d[1]<<" "<<d[2]<<endl;    return 0; }

 

*遍曆

 #include<iostream> #include<deque> using namespace std; int main() {    deque<int> d;    d.push_back(1);    d.push_back(2);    d.push_back(3);    for(int i = 0; i < d.size(); i ++)        cout<<d[i]<<" ";    cout<<endl;    deque<int>::iterator it;    for(it = d.begin(); it != d.end(); it ++)        cout<<*it<<" ";    cout<<endl;    deque<int>::reverse_iterator rit;    for(rit = d.rbegin(); rit != d.rend(); rit ++)        cout<<*rit<<" ";    cout<<endl;    return 0; }

 

*刪除元素 
可以從雙端隊列的手部,尾部,中部刪除元素,並可以清空雙端隊列容器

#include<iostream>#include<deque>using namespace std;int main(){    deque<int> d;    for(int i = 1; i < 6; i ++)        d.push_back(i);    d.pop_front();    d.pop_front();    deque<int>::iterator it;    for(it = d.begin(); it != d.end(); it ++)        cout<<*it<<" ";    cout<<endl;    d.pop_back();    for(it = d.begin(); it != d.end(); it ++)        cout<<*it<<" ";    cout<<endl;    d.erase(d.begin()+1);    for(it = d.begin(); it != d.end(); it ++)        cout<<*it<<" ";    cout<<endl;    d.clear();    cout<<d.size()<<endl;    return 0;} 

 

C++STL之雙端隊列容器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.