您的位置:首页 > 编程语言 > C语言/C++

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 答案