孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1.序列容器

STL序列容器有

  • vector<T>  提供对变长序列的随机访问,插入和删除操作时间均为分摊常量
  • deque<T>  提供对变长序列的随机访问,插入和删除操作时间均为分摊常量
  • list<T>  提供对变长序列的线性访问(O(N)),但是对任意位置的插入和删除为常量时间

示例1:对cstring和数组使用STL类属算法reverse

1 #include <iostream>
2 #include <string.h>
3 #include <cassert>
4 #include <algorithm>
5  using namespace std;
6
7  int main()
8 {
9 cout<<"Using reverse algorithm with a string"<<endl;
10 string string1="mark twain";
11 reverse(string1.begin(),string1.end());
12 assert(string1=="niawt kram");
13 cout<<" --- OK."<<endl;
14
15 cout<<"Using reverse algorithm with an array"<<endl;
16 char array1[]="mark twain";
17 int N1=strlen(array1);
18 reverse(&array1[0],&array1[N1]);
19 assert(string(array1)=="niawt kram");
20 cout<<" --- OK."<<endl;
21 return 0;
22 }

示例2:对向量使用STL类属算法reverse

1 dongjichao@dongjichao:~/c$ cat ex02-02.cpp
2 #include <iostream>
3 #include <vector>
4 #include <cstring>
5 #include <cassert>
6 #include <algorithm>
7  using namespace std;
8
9 template <typename Container>
10 Container make(const char s[])
11 {
12 return Container(&s[0],&s[strlen(s)]);
13 }
14
15  int main()
16 {
17 cout<<"Using reverse algorithm with a vector"<<endl;
18 vector<char> vector1=make< vector<char> >("mark twain");
19 reverse(vector1.begin(),vector1.end());
20 assert(vector1==make< vector<char> >("niawt kram"));
21 cout<<" --- OK."<<endl;
22 return 0;
23 }

示例3:对list使用STL类属算法reverse

1 #include <iostream>
2 #include <cassert>
3 #include <list>
4 #include <algorithm>
5 #include <cstring>
6  using namespace std;
7
8 template <typename Container>
9 Container make(const char s[])
10 {
11 return Container(&s[0],&s[strlen(s)]);
12 }
13
14  int main()
15 {
16 cout<<"Demonstracting generic reverse algorithm on a list"<<endl;
17 list<char> list1=make< list<char> >("mark twain");
18 reverse(list1.begin(),list1.end());
19 assert(list1==make< list<char> >("niawt kram"));
20 cout<<" --- OK."<<endl;
21 return 0;
22 }

2.有序关联容器

有序关联容器有4类

  • set<Key>  支持唯一的键并提供对键本身的快速检索
  • multi<Key>  支持可重复的键,并提供对键本身的快速检索
  • map<Key,T>  支持唯一的键并提供对另一个基于键的类似T的快速检索
  • multimap<Key,T>  支持可重复的键并提供对另一个基于键的类似T的快速检索

示例4:演示STL映射

1 #include <iostream>
2 #include <map>
3 #include <string>
4  using namespace std;
5
6  int main()
7 {
8 map<string,long> directory;
9 directory["Bogart"]=1234567;
10 directory["Bacall"]=9876543;
11 directory["Cagney"]=3459876;
12 //And son on
13 //Read name;
14   string name;
15 while (cin >> name)
16 if (directory.find(name) !=directory.end())
17 cout<<"The phone number for "<<name<<" is "<<directory[name]<<"\n";
18 else
19 cout<<"Sorry, no listing for "<<name <<"\n";
20 return 0;
21 }

编译,运行,输入一个名称如 Bogart,会给出对应的序号

$ ./ex02-04
Bogart
The phone number for Bogart is 1234567
^Z

posted on 2011-05-23 20:18  孤独的猫  阅读(255)  评论(0编辑  收藏  举报