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

C++Primer第五版 练习11.14(解答)

2015-09-29 14:27 387 查看
练习11.14:扩展你在11.2.1节练习(第378页)中编写的孩子姓到名的map,添加一个pair的vector,保存孩子的名和生日。

参考练习11.7

C++Primer第五版 练习11.7(解答)

/*
*练习11.14.cpp
*2015/9/29
*问题描述:
练习11.14:扩展你在11.2.1节练习(第378页)中编写的孩子姓到名的map,添加一个pair的vector,保存孩子的名和生日。
练习11.7:定义一个map,关键字是家庭的姓,值是一个vector,保存家中孩子(们)的名。编写代码,实现添加新的家庭以及向已有家庭中添加新的孩子。
*说明:弄清楚pair的类型,map的类型
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*/

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <utility>

using namespace std;

//定义一个Date类,表示生日,需要说明的是,该Date类很简单,没有做类型检查
struct Date{
int year;
int month;
int day;
Date() = default; //空构造函数不写,后果很严重,不妨注释掉看看
Date(int y,int m,int d) : year(y), month(m), day(d)
{
}
void print(){
cout << year << "-" << month << "-" << day << endl;
}
};

int main()
{
string fname;
string name;
int year,month,day;
pair<string,Date> p; //pair保存孩子的名和生日

//该类型稍复杂,关键字string类型,用于保存家族姓氏
//第二个元素是vector中存放pair保存孩子的名和生日向量
map<string,vector<pair<string,Date>>> family;

//依次输入姓氏,名字,年,月,日
while(cin >> fname >> name >> year >> month >> day)
{
Date d(year,month,day);
p = {name,d};
family[fname].push_back(p);
}

for(auto &member : family)
{
cout << "Member is:" << " " << endl;
for(auto it = member.second.begin(); it != member.second.end();++it)
cout << (*it).first << "." << member.first << " " << (*it).second.year << "-" << (*it).second.month << "-" << (*it).second.day << endl;
cout << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息