c++ deque
- A deque is a double-ended queue
- Insertion at the front and back is fast
- Random access is fast
- Start:
- push_front(0);
- push_front(1);
push_front(2);
push_front(3);
- push_front(4);
- push_back(0);
- push_back(1);
push_back(2);
push_back(3);
- push_back(4);
- push_front(5);
push_front(6);
push_front(7);
push_front(8);
- C++ deque usage
1:// cppDequeExample.cpp - download here
2:
3:#include<deque>
4:#include<iostream>
5:
6:intmain(intargc,char*argv[]){
7:
8:std::deque<int>dq1;
9:dq1.push_front(1);
10:dq1.push_front(2);
11:dq1.push_back(3);
12:
13:for(size_ti=0;i<dq1.size();++i){
14:std::cout<<dq1[i]<<" ";
15:}
16:
17:return0;
18:}
- Deque Algorithms
1:
2:voidDeque::push_back(intvalue){
3:if(m_LastBlockStop==m_BlockSize){
4:m_MiddleBlocks.push_back(m_LastBlock);
5:m_LastBlockStop=0;
6:m_LastBlock=newint[m_BlockSize];
7:}
8:m_LastBlock[m_LastBlockStop]=value;
9:++m_LastBlockStop;
10:++m_Size;
11:}
12:
13:voidDeque::push_front(intvalue){
14:if(m_FirstBlockStart==m_BlockSize){
15:m_MiddleBlocks.push_front(m_FirstBlock);
16:m_FirstBlockStart=0;
17:m_FirstBlock=newint[m_BlockSize];
18:}
19:m_FirstBlock[m_BlockSize-m_FirstBlockStart-1]=value;
20:++m_FirstBlockStart;
21:++m_Size;
22:}
23:
24:int*Deque::getBlock(intblock_index){
25:std::list<int*>::iteratoriter=m_MiddleBlocks.begin();
26:for(inti=0;i<block_index;++i){
27:++iter;
28:}
29:return*iter;
30:}
31:
32:intDeque::get(intindex){
33:if(index<m_FirstBlockStart){
34:intblock_index=m_BlockSize-m_FirstBlockStart+index;
35:returnm_FirstBlock[block_index];
36:}elseif(index<m_Size-m_LastBlockStop){
37:index-=m_FirstBlockStart;
38:intblock=index/m_BlockSize;
39:int*curr=getBlock(block);
40:intitem=index%m_BlockSize;
41:returncurr[item];
42:}else{
43:intlast_index=index-m_FirstBlockStart-(m_MiddleBlocks.size()*m_BlockSize);
44:returnm_LastBlock[last_index];
45:}
46:}
47: -