官术网_书友最值得收藏!

  • Mastering C++ Programming
  • Jeganathan Swaminathan
  • 281字
  • 2021-07-02 18:28:51

Deque

The deque container is a double-ended queue and the data structure used could be a dynamic array or a vector. In a deque, it is possible to insert an element both at the front and back, with a constant time complexity of O(1), unlike vectors, in which the time complexity of inserting an element at the back is O(1) while that for inserting an element at the front is O(N). The deque doesn't suffer from the problem of reallocation, which is suffered by a vector. However, all the benefits of a vector are there with deque, except that deque is slightly better in terms of performance as compared to a vector as there are several rows of dynamic arrays or vectors in each row.

The following diagram shows the internal data structure used in a deque container:

Let's write a simple program to try out the deque container:

#include <iostream>
#include <deque>
#include <algorithm>
#include <iterator>
using namespace std;

int main () {
deque<int> d = { 10, 20, 30, 40, 50 };

cout << "\nInitial size of deque is " << d.size() << endl;

d.push_back( 60 );
d.push_front( 5 );

cout << "\nSize of deque after push back and front is " << d.size() << endl;

copy ( d.begin(), d.end(), ostream_iterator<int>( cout, "\t" ) );
d.clear();

cout << "\nSize of deque after clearing all values is " << d.size() <<
endl;

cout << "\nIs the deque empty after clearing values ? " << ( d.empty()
? "true" : "false" ) << endl;

return 0;
}

The output can be viewed with the following command:

./a.out

The output of the program is as follows:

Intitial size of deque is 5

Size of deque after push back and front is 7

Print the deque ...
5 10 20 30 40 50 60
Size of deque after clearing all values is 0

Is the deque empty after clearing values ? true
主站蜘蛛池模板: 黄浦区| 娄烦县| 贺兰县| 古丈县| 白水县| 调兵山市| 凉山| 清流县| 天门市| 六枝特区| 廊坊市| 左云县| 蚌埠市| 浠水县| 肥西县| 福清市| 富锦市| 吉水县| 富锦市| 莎车县| 古蔺县| 马山县| 会昌县| 板桥市| 沾益县| 遂平县| 青浦区| 汉沽区| 水城县| 昌黎县| 买车| 浏阳市| 拜泉县| 庆阳市| 广丰县| 宁南县| 鄂伦春自治旗| 兴国县| 鄂托克旗| 合作市| 恭城|