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

  • 相关阅读:
    自定义Spark Partitioner提升es-hadoop Bulk效率
    golang channel本质——共享内存
    STM 软件事务内存——本质是为提高并发,通过事务来管理内存的读写访问以避免锁的使用
    elasticsearch 自定义_id
    JS弄ASP.NET(C#)在页GridView信息选择行
    pdf转换为word小工具,挺好
    Cocos2d-x场景功能描述的生命周期
    数据收集程序一般建筑(C++ ACE达到)
    IOS上传文件开发
    thinkphp达到UploadFile.class.php图片上传功能
  • 原文地址:https://www.cnblogs.com/NaughtyBaby/p/3937351.html
Copyright © 2011-2022 走看看