演示STL双端队列的push_back和push_front函数

双端队列(deque)和向量没有多少区别。它们主要的区别在性能上:和向量相比,在双端队列起点上的插入和删除操作要快的多,其时间复杂度仅为常数。所有的STL类属方法都可用于双端队列。下面为push_back和push_front函数的列子:


1 #include <iostream>
2 #include <cassert>
3 #include <string>
4 #include <deque>
5 #include <algorithm> // for reverse
6  using namespace std;
7 template <typename Container>
8 Container make(const char s[])
9 {
10 return Container(&s[0], &s[strlen(s)]);
11 }
12
13 int main()
14 {
15 deque<char> deque1 =
16 make< deque<char> >("Bjarne Stroustrup"),
17 deque2;
18 deque<char>::iterator i;
19
20 cout << "Demonstrating deque push_back function" << endl;
21 for (i = deque1.begin(); i != deque1.end(); ++i)
22 deque2.push_back(*i);
23 assert (deque1 == deque2);
24
25 deque1 = make< deque<char> >("Bjarne Stroustrup");
26 deque2 = make< deque<char> >("");
27
28 cout << "Demonstrating deque push_front function" << endl;
29 for (i = deque1.begin(); i != deque1.end(); ++i)
30 deque2.push_front(*i);
31 assert (deque2 == make< deque<char> >("purtsuortS enrajB"));
32
33 // Show that deque2 is the reverse of deque1 by using
34 // STL generic reverse function to reverse deque1:
35 reverse(deque1.begin(), deque1.end());
36 assert (deque2 == deque1);
37 cout << " --- Ok." << endl;
38 return 0;
39 }
上一篇:JVM14_Class文件结构细节、魔数、Class文件版本、常量池、访问标识(或标志)、类索引|父类索引|接口索引集合、字段|方法|属性表集合(一)


下一篇:JVM14_Class文件结构细节、魔数、Class文件版本、常量池、访问标识(或标志)、类索引|父类索引|接口索引集合、字段|方法|属性表集合(三)