目录
第十一章 关联容器
11.1 使用关联容器(11.1 ~ 11.4)
11.2 关联容器概述
11.2.1 定义关联容器(11.5 ~ 11.8)
11.2.2 关键字类型的要求(11.9 ~ 11.11)
未完待续
工作的间隙看的,所以输出比较慢,希望能巩固基础,再往后深入。
一直有参考这位同学的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:
// 统计每个单词在输入中出现的次数 mapword_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; }
11.4:
mapword_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; }
11.2 关联容器概述
11.2.1 定义关联容器(11.5 ~ 11.8)
11.5:
map是关键字-值对的集合。set是关键字的简单集合。当只想知道一个值是否存在时,set是最有用的。
11.6:
set是关键字的简单集合,set中的元素不可以重复。list是双向链表,支持任意位置 插入删除。
11.7:
map> name_map; name_map.insert(make_pair >("James", vector ())); name_map.insert(make_pair >("Jane", vector ({"Austen"}))); name_map.insert(make_pair >("Charles", vector ())); 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; }
11.8:
vectorwords = {"the", "quick", "red", "fox", "jumps", "over", "the", "slow", "red", "turtle"}; auto p = [](const vector & 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); } }
11.2.2 关键字类型的要求(11.9 ~ 11.11)
11.9:
map> words_lines;
11.10:
vector可以,list不可以,因为vector的迭代器定义了比较大小的操作,而list的迭代器没有。
11.11:
struct Sales_data {
std::string isbn() const { return bookNo; }
std::string bookNo;
};
using compareType = bool (*)(const Sales_data& lhs, const Sales_data& rhs);
bool compareIsbn(const Sales_data& lhs, const Sales_data& rhs) {
return lhs.isbn() < rhs.isbn();
}
multiset bookstore(compareIsbn);
int main()
{
Sales_data a, b;
a.bookNo = "aaaa";
b.bookNo = "bbbb";
bookstore.insert(b);
bookstore.insert(a);
for(const auto& book : bookstore){
cout << book.isbn() << endl;
}
}



