11.2.1节练习
来源:互联网 发布:物联网数据采集与处理 编辑:程序博客网 时间:2024/06/05 15:41
练习11.5 解释map和set的区别。你如何选择使用哪个。
set就好比我有一个陆军集团军,里面有步兵,炮兵。
而map好比我有海陆空三军,其中陆军有步兵,海军有海豹部队,空军有伞兵。
用set解决不了的情况用map。
练习11.6 解释set和list的区别。你如何选择使用哪个?
索引不同。
需要访问整个容器用list,查找特定元素用set。
练习11.7定义一个map,关键字是家庭的姓,值是一个vector,保存家中孩子(们)的名。编写代码,实现添加新的家庭以及向己有家庭中添加新的孩子。
#include <iostream>#include <string>#include <map>#include <vector>#include <iterator>#include <algorithm>using namespace std;int main(){map<string, vector<string>> name = {{"Paul",{"Pierce","Christ"}},{"Green",{"Jogre"}}};string fir, sec;while (cin >> fir >> sec) {//利用Push_back往容器添加元素。name[fir].push_back(sec);}for (auto &i : name) {cout << i.first << " family: ";// i.second 是vector ,再次使用范围for循环。for (auto &c : i.second) {cout << c << " ";}cout << endl;}return 0;}
练习11.8 编写一个程序,在一个vector而不是set中保存不重复的单词。使用set的优点是什么?
set不必再判断单词是否在容器内,自动删选。
而vector要程序员编写代码遍历容器。
#include <iostream>#include <vector>#include <string>using namespace std;int main(){vector<string> text{ "one","two" };string word;while (cin >> word) {auto iter = find(text.cbegin(), text.cend(), word);if (iter == text.cend()) {text.push_back(word);}}for (auto i : text) {cout << i << " ";}cout << endl;return 0;}
0 0
- 11.2.1节练习
- 第十一章 11.2.1节练习
- 11.2.2节练习
- 11.2.3节练习
- 10.2.1节练习
- 10.3.1节练习
- 10.4.1节练习
- 10.5.1节练习
- 11.3.1节练习
- 1.5.1节练习
- 2.1.1节练习
- 2.2.1节练习
- 2.3.1节练习
- 2.6.1节练习
- 5.3.1节练习
- 第十五章 15.8.1节练习 & 15.9.1节练习
- 第七章 7.2.1节练习 & 7.3.1节练习
- 第九章 9.5.1节练习 & 9.5.2节练习
- 对handler的一些简单理解
- JSP第二篇
- 一致性哈希算法分析
- 大型网站的架构设计详解4
- 安卓基本控件和布局使用
- 11.2.1节练习
- Caffe 实例笔记 1 CaffeNet从训练到分类及可视化参数特征 微调
- 设计模式笔记-Visitor访问者模式
- c++作业7
- Linux 系统内核的调试
- 怎样和未来导师“套磁”?
- JAVA基础面试
- leetcode 219 Contains Duplicate II C++
- 文件复制缓冲与不缓冲的区别