Deque two-way queue is a kind of continuous linear space with two-way opening, which can insert and delete elements at both ends of the head and tail efficiently. Deque is very similar to vector in interface. The common member functions of deque are listed below:
The implementation of deque is complex, and a map will be maintained internally! It is not a map container in STL), that is, a small piece of continuous space. Each element in the space is a pointer, pointing to another (larger) area, which is called a buffer. The buffer is used to store the data in deque. Therefore, deque is slower than vector in random access and traversal of data. Specific deque implementation can refer to STL source code analysis, of course, the SGI STL used in this book is different from the PJ STL used in VS2008. The structure of deque is shown as follows:
Due to the space problem, the implementation details of deque are no longer in-depth. Here is an example of deque:
- //Two way queue deque
- //by MoreWindows http://blog.csdn.net/morewindows
- #include <deque>
- #include <cstdio>
- #include <algorithm>
- using namespace std;
- int main()
- {
- deque<int> ideq(20); //Create a deque ideq with 20 elements of default value 0
- deque<int>::iterator pos;
- int i;
- //Assign using assign() means assign in the computer
- for (i = 0; i < 20; ++i)
- ideq[i] = i;
- //Output deque
- printf("output deque Medium data:\n");
- for (i = 0; i < 20; ++i)
- printf("%d ", ideq[i]);
- putchar('\n');
- //Add new data at the beginning and end
- printf("\n Add new data at the beginning and end...\n");
- ideq.push_back(100);
- ideq.push_front(i);
- //Output deque
- printf("\n output deque Medium data:\n");
- for (pos = ideq.begin(); pos != ideq.end(); pos++)
- printf("%d ", *pos);
- putchar('\n');
- //lookup
- const int FINDNUMBER = 19;
- printf("\n lookup%d\n", FINDNUMBER);
- pos = find(ideq.begin(), ideq.end(), FINDNUMBER);
- if (pos != ideq.end())
- printf("find %d success\n", *pos);
- else
- printf("find failed\n");
- //Delete data at the beginning and end
- printf("\n Delete data at the beginning and end...\n");
- ideq.pop_back();
- ideq.pop_front();
- //Output deque
- printf("\n output deque Medium data:\n");
- for (pos = ideq.begin(); pos != ideq.end(); pos++)
- printf("%d ", *pos);
- putchar('\n');
- return 0;
- }
The operation results are as follows:
One more thing to note. For deque and vector, use erase(pos) and erase(beg,end) as little as possible. Because this will lead to data moving forward after deleting data in the middle, which makes the efficiency low.
Please indicate the source of reprint, original address: http://blog.csdn.net/morewindows/article/details/6946811