C++primer 11.2.3节练习解答11.12-11.14
2016-10-12 16:12
176 查看
C++primer 11.2.3节练习解答11.12-11.14
练习11.12:编写程序,读入string和int的序列,将每个string和int存入一个pair中,pair保存在一个vector中。练习11.13:在上一题的程序中,至少有三种创建pair的方法。编写此程序的三个版本,分别采用不同的方法创建pair。解释你认为哪种形式最易于编写和理解,为什么?
练习11.14:扩展你在11.2.1节练习(第378页)中编写的孩子姓到名的map,添加一个pair的vector,保存孩子的名和生日。
#include <iostream> #include <string> #include <vector> #include <map> #include <utility> using namespace std; //编写程序,读入string和int的序列,将每个string和int存入一个pair中,pair保存在一个vector中。 void exercise12() { string word; int num; vector<pair<string, int>> vecs; cout << "please input a string: "; while (cin>>word) { cout <<endl<< "please input a int: "; cin >> num; //vecs.push_back({ word, num });//特点是简洁 //vecs.push_back(make_pair(word, num));//特点是容易理解 vecs.push_back( pair<string, int>(word, num));//特点是易读 cout << endl << "continue ? Y/N: "; char c = 'Y'; cin >> c; if (c == 'N' || c == 'n') break; cout <<endl<< "please input a string: "; } for (const auto &vec : vecs) cout << vec.first << " " << vec.second << endl; } //编写的孩子姓到名的map,添加一个pair的vector,保存孩子的名和生日。 void exercise14() { string family,name,birthday; map<string, vector<pair<string, string>>> maps; cout << "please input a family name: "; while (cin >> family) { vector<pair<string, string>> vecs = {}; cout << endl << "please input a child name : "; while (cin >> name) { cout << endl << "please input his birthday: "; cin >> birthday; vecs.push_back({ name, birthday }); cout << endl << "continue add child ? Y/N: "; char c = 'Y'; cin >> c; if (c == 'N' || c == 'n') break; cout << endl << "please input a child name : "; } maps[family] = vecs; cout << endl << "continue add family ? Y/N: "; char c = 'Y'; cin >> c; if (c == 'N' || c == 'n') break; cout << endl << "please input a family name : "; } for (const auto &mapn : maps) { cout << mapn.first << endl; for (const auto &vec : mapn.second) cout << vec.first << " " << vec.second << ends; cout << endl; } } void main() { //exercise12(); exercise14(); }
ok ! Mark 一下第一篇 blog !
相关文章推荐
- C++Primer第五版 练习11.12(解答)
- C++Primer第五版 练习11.14(解答)
- C++Primer第五版 11.2.3节练习(解答)
- C++Primer第五版 第1章 开始(练习解答)
- C++Primer第五版 练习11.3(解答)
- C++Primer第五版 1.2节练习(解答)
- C++Primer第五版 练习11.4(解答)
- C++Primer第五版 练习11.13(解答)
- C++Primer第五版 第4章 表达式(练习解答)
- C++Primer第五版 练习11.9(解答)
- C++Primer第五版 第6章 函数(练习解答)
- C++Primer第五版 练习11.10(解答)
- C++Primer第五版 练习11.31-32(解答)
- C++Primer 第五版 练习10.12解答
- C++Primer第五版 练习11.11(解答)
- c++primer 课后练习解答网址
- C++Primer第五版 练习11.25(解答)
- C++Primer第五版 第7章 类(练习解答)
- C++Primer第五版 第9章 顺序容器(练习解答)
- C++Primer第五版 练习11.26(解答)