在标准 C++类库中,双向队列类(deque)的成员函数 queue::insert()往一个双向队列中插入元素,queue::push_front(const T& x)往一个双向队列的头端插入一个元素, queue::pop_front()从一个双向队列的头端删除一个元素,queue::push_back(const T& x)往一个双向队列的尾端插入一个元素,queue::pop_back(const T& x)从一个双向队列的尾端删除一个元素,请构造一个字符型双向队列,体会这几个成员函数的用法。

解:
#include <iostream> #include <deque> using namespace std; typedef deque<char > CHARDEQUE; void print_contents (CHARDEQUE deque); void main() { //create a with 3 A's CHARDEQUE a(3,'A'); //create b with 2 B's. CHARDEQUE b(2,'B'); //print out the contents print_contents (a); print_contents (b); //insert 'X' to the beginning of a a.insert(a.begin(),'X'); print_contents (a); //insert 'Y' to the end of a a.insert(a.end(),'Y'); print_contents (a); //inset 3 'Z's to one item before the end of a a.insert(a.end()-1,3,'Z'); print_contents (a); //insert to the end of a from b a.insert(a.end(),b.begin(),b.end()); print_contents (a); } //function to print the contents of deque void print_contents (CHARDEQUE deque) { CHARDEQUE::iterator pdeque; cout <<"The output is: "; for(pdeque = deque.begin(); pdeque != deque.end(); pdeque++) { cout << *pdeque <<" " ; } cout<<endl; }程序运行输出:
The output is: A A A
The output is: B B
The output is: X A A A
The output is: X A A A Y
The output is: X A A A Z Z Z Y
The output is: X A A A Z Z Z Y B B