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

练习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;   
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值