zoukankan      html  css  js  c++  java
  • 读取文件并找出年龄最大的N个人-兰亭集市笔试题

    C++ code:

    #include <iostream>
    #include <fstream>
    #include <map>
    #include <string>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        multimap<int,string> agemap;//以年龄为键,以个人信息为值,年龄必有重复,定义成multimap可自动排序
        ifstream infile("persons.txt");//为ifstream对象提供文件名作为初始化式,就相当于打开了特定的文件,不用再调用open函数
        if(!infile)
        {
            cout<<"Open file error!"<<endl;
        }
    
        string textline;
        int age;
        string::reverse_iterator rcomma;//string类型反向迭代器,用于指向反向搜索找到的第一个逗号
        while(getline(infile,textline))//getline函数将istream参数作为返回值,可用作读取结束判断条件
        {
            rcomma=find(textline.rbegin(),textline.rend(),',');//rcomma指向从后往前的最后一个逗号
            age=atoi(string(rcomma.base(),textline.end()).c_str());//string转int,rcomma.base()表示将反向迭代器rcomma转换为从前往后移动的普通迭代器
            agemap.insert(make_pair(age,textline));//将年龄和完整信息插入multimap
        }
    
        multimap<int,string>::reverse_iterator map_it=agemap.rbegin();//从后往前输出
    
        int N=10;//假定要输出年龄最大的前10个
        while(map_it!=agemap.rend() && N-- >0)//按年龄降序输出元素
        {
            cout<<map_it->second<<endl;
            ++map_it;
        }
    
        return 0;
    }



    persons.txt

    Ted Elliott,9876541198611121512,27
    Peter Twist,52478198901243122,24
    Terry Rossio,456871198804096012,25
    George Marshall Ruge,510402198904070919,24
    Brian Morris,51068119830104411X,30
    Christopher Masterson,432502198908193032,24
    Mel Colm-Cille Gerard Gibson,431102198911046233,24
    Tim,511621198603095910,27
    gdfgdf,371326198806230018,25
    gdfg,41150219871015966X,26
    gdfdf,620422198801191911,25
    gdfgfd,411325198710241333,26
    gdff,140522198804301013,25
    gdfg,230204198801180714,25
    dfgfd,510704198706063514,26
    gfdgdf,610424198906172881,24
    gdfgfd,513922198511210031,28
    uykuy,320911198901061214,24
    jghjj,51302919890906659X,24
    jhhjh,612731198809280436,25
    jhgjhg,650103198902056022,24
    jghg,51070319790525972X,34
    jghjh,510681198810130315,25
    hgjhg,510304198706071010,26
    jghjhg,320382198708300431,26
    jhgjg,340321198903154709,24

  • 相关阅读:
    PHP 大小写转换、首字母大写、每个单词首字母大写转换相关函数
    【论文学习4】BiSample: Bidirectional Sampling for Handling Missing Data with Local Differential Privacy
    【论文学习3】Local Differential Privacy for Deep Learning
    【论文学习2】 Differential Privacy Reinforcement Learning
    深度学习中的优化算法
    Spatial crowdsourcing
    “pip install tensorflow ”出现错误
    python或pip'不是内部或外部命令”
    pip install torch出现错误
    打不开gitHub的解决方法
  • 原文地址:https://www.cnblogs.com/NaughtyBaby/p/3937351.html
Copyright © 2011-2022 走看看