目录
11.3.4 map的下标操作(11.24 ~ 11.26)
11.3.6 一个单词转换的map(11.33 ~ 11.36)
工作的间隙看的,所以输出比较慢,希望能巩固基础,再往后深入。
一直有参考这位同学的blog的答案:C++Primer第五版——习题答案+详解(完整版)_MISAYAONE的博客-CSDN博客,不过好像这位同学看的很快有很一些些不是很正确,看评论也有都一一修正。
这个答案也是自己看书然后输出的,也可能有问题,如果有发现什么问题,欢迎评论一起讨论!!
默认大家都有了第5版的纸质书或电子书,这里就只记录题号和答案(其实对原书的截图有点侵犯版权的感觉,狗头保命)
第十一章 关联容器
11.1 使用关联容器(11.1 ~ 11.4)
11.1:
map中的元素是按关键字来保存和访问的,vector中的元素是按它们在vector中的位置来顺序保存和访问的。
11.2:
list:任意位置任意删除添加数据
vector:普通数组,相关联数据,顺序处理
deque:信息处理,只在头部
map:存储字典型数据
set:坏值检验,只有关键字的好处
11.3:
// 统计每个单词在输入中出现的次数
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) { // 对map中的每个元素
// 打印结果
cout << w.first << " occurs " << w.second;
auto str = (w.second > 1) ? " times" : " time";
cout << str << endl;
}
/*
Although Before an and
^Z
Although occurs 1 time
Before occurs 1 time
an occurs 1 time
and occurs 1 time
*/
11.4:
map<string, size_t> word_count;
string word;
while(cin >> word) {
// 忽略大小写
for(auto it = word.begin(); it != word.end(); it++) {
*it = tolower(*it);
}
// 忽略标点符号
for(auto it = word.begin(); it != word.end(); ) {
if(ispunct(*it)){
it = word.erase(it);
}
else{
it++;
}
}
++word_count[word];
}
for(const auto& w : word_count) {
cout << w.first << " occurs " << w.second;
auto str = (w.second > 1) ? " times" : " time";
cout << str << endl;
}
/*
example. example, Example
^Z
example occurs 3 times
*/
11.2 关联容器概述
11.2.1 定义关联容器(11.5 ~ 11.8)
11.5:
map是关键字-值对的集合。set是关键字的简单集合。当只想知道一个值是否存在时,set是最有用的。
11.6:
set是关键字的简单集合,set中的元素不可以重复。list是双向链表,支持任意位置 插入删除。
11.7:
map<string, vector<string>> name_map;
name_map.insert(make_pair<string, vector<string>>("James", vector<string>()));
name_map.insert(make_pair<string, vector<string>>("Jane", vector<string>({"Austen"})));
name_map.insert(make_pair<string, vector<string>>("Charles", vector<string>()));
auto name_vec = name_map.find("James");
if(name_vec != name_map.end()) {
name_vec->second.push_back("Joyce");
name_vec->second.push_back("Dickens");
}
for(const auto& v : name_map) {
cout << "家庭的姓: " << v.first << " ";
auto names = v.second;
if(names.size() <= 0) {
cout << endl;
continue;
}
cout << "孩子的名: ";
for(const auto& name : names) {
cout << name << " ";
}
cout << endl;
}
/*
家庭的姓: Charles
家庭的姓: James 孩子的名: Joyce Dickens
家庭的姓: Jane 孩子的名: Austen
*/
11.8:
vector<string> words = {"the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle"};
auto p = [](const vector<string>& ws){
cout << "现有单词: ";
for(const auto& w : ws) {
cout << w << " ";
}
cout << endl;
};
p(words);
string word;
while(cin >> word) {
if(find(words.begin(), words.end(), word) != words.end()) {
cout << "不支持保存重复单词" << endl;
}
else{
words.push_back(word);
p(words);
}
}
/*
现有单词: the quick red fox jumps over the slow red turtle
the
不支持保存重复单词
quick
不支持保存重复单词
about
现有单词: the quick red fox jumps over the slow red turtle about
right
现有单词: the quick red fox jumps over the slow red turtle about right
*/