c++primer 12.23答案

本文介绍了如何在Ubuntu环境下,使用C++的multimap结构和fstream读取文件used1.txt,并将其中的姓名与生日对按照姓氏分组存储。作者展示了如何逐行解析文件并使用`insert()`方法添加数据到multimap中。
摘要由CSDN通过智能技术生成

        题干分析:用multimap,所以不能用[]来添加,需使用instert(),注意,初始化需直接传入一个pair。

        本答案中为Ubuntu下,所以文件输入流初始化的文件路径是”../used1.txt“,及used1.txt文件,在.bin文件所在路径的上一级路径。

        下面红色背景文字内容是used1.txt文件的内容(每一条是单独的一行):

 赵 赵以 2000/8/8 赵二 2001/9/5 
 钱 钱三 2000/8/1
 孙 孙思 2000/3/22 孙无 2000/1/1
李 李六 2000/8/18 李其 2000/2/2 李吧 2000/3/5

下面是代码答案:

/**
****************************************************************************************
* @FilePath: main.cpp
* @Author: YMM
* @Date: 2024-03-22 22:29:06
* @LastEditors: YMM
* @LastEditTime: 2024-03-28 13:01:40
* @Copyright: 2024 xxxTech CO.,LTD. All Rights Reserved.
* @Descripttion:
****************************************************************************************
*/
#include "../include/main.h"

using namespace std;
using namespace std::placeholders; // bind _

int main()
{
#ifdef DEBUG
    cout << "****************DEBUG  BEGIN***************" << endl;
    cout << "Source file path:" << __FILE__ << endl;
    cout << "Compiling date:" << __DATE__ << endl;
    cout << "Compile time:" << __TIME__ << endl;
#endif // DEBUG

    multimap<string,vector<pair<string,string>>> ChildrenBirthday;
    ifstream ifs("../used1.txt");
    string linestr;
    string surname,Name,Birthday;
    while(getline(ifs,linestr))
    {
        istringstream iss(linestr);
        vector<pair<string,string>> NameBirthday;
        iss>>surname;
        while(iss>>Name>>Birthday)
        {
            NameBirthday.push_back({Name,Birthday});
        }
        ChildrenBirthday.insert(make_pair(surname,NameBirthday));
    }
    for(const auto&i:ChildrenBirthday)
    {
        cout<<i.first<<"姓:";
        for(const auto&j:i.second)
        {   
            cout<<j.first<<"生日:"<<j.second;
        }
        cout<<endl;
    }
}

  • 17
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值