练习11.1:描述map和vector的不同。
答:关联容器map中的元素是按关键字来保存和访问的。
与之相对,顺序容器vector中的元素是按它们在容器中的位置来顺序保存和访问的。
练习11.2:分别给出最适合使用list,vector,deque,map以及set的例子。
答:list 表单
vector 顺序方面元素
deque 队列
map 关键字-值,字典
set 在文本处理过程中,可以用来保存想要忽略的单词。
练习11.3:编写你自己的单词记数程序
答:见练习11_3.cpp
/*
*C++Primer(第五版)
*练习11.3
*2015/9/22
*问题描述:练习11.3:编写你自己的单词记数程序
*说明:照着P375页copy了一遍
*作者:Nick Feng
*邮箱;nickgreen23@163.com
*/
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<string, size_t> word_count; //string到size_t的空map
string word;
while(cin >> word)
++word_count[word]; //提取word的计数器并将其加1
for(const auto &w : word_count)
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;
return 0;
}
练习11.4:扩展你的程序,忽略大小写和标点,例如,“example.”,“example,”和“Example”应该计数递增相同的计数器。
答:见练习11_4.cpp
/*
*C++Primer(第五版)
*练习11.3
*2015/9/22
*问题描述:练习11.4:扩展你的程序,忽略大小写和标点。例如,"example.","example,"和"Example"应该计数递增相同的计数器。
附:练习11.3:编写你自己的单词记数程序
*说明:照着P375页copy了一遍
*作者:Nick Feng
*邮箱;nickgreen23@163.com
*/
#include <iostream>
#include <string>
#include <map>
#include <set>
using namespace std;
int main()
{
map<string, size_t> word_count;
set<string> exclude = {"example.","example,","Example"};//要被忽略计数的单词
string word;
while(cin >> word)
if(exclude.find(word) == exclude.end()) //修改部分
++word_count[word];
for(const auto &w : word_count)
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;
return 0;
}