H106OJ | 身份证排序(c++版)

H106OJ | 身份证排序(c++)

问题描述

Description
安全局搜索到了一批(n个)身份证号码,希望按出生日期对它们进行从大到小排序,如果有相同日期,则按身份证号码大小进行排序。身份证号码为18位的数字组成,出生日期为第7到第14位
Input
第一行一个整数n,表示有n个身份证号码
余下的n行,每行一个身份证号码。
Output
按出生日期从大到小排序后的身份证号,每行一条
Sample Input 1
5
466272307503271156
215856472207097978
234804580401078365
404475727700034980
710351408803093165
Sample Output 1
404475727700034980
234804580401078365
215856472207097978
710351408803093165
466272307503271156
Hint
HINT:时间限制:1.0s 内存限制:256.0MB
n<=100000

问题分析

核心:sort函数使用;
c++关于sort函数定义:

template <class RandomAccessIterator>
  void sort (RandomAccessIterator first, RandomAccessIterator last);
template <class RandomAccessIterator, class Compare>
  void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

第一种使用:
默认升序

int myints[] = {32,71,12,45,26,80,53,33};
vector<int> myvector (myints, myints+8);// 32 71 12 45 26 80 53 33

// using default comparison (operator <):
sort (myvector.begin(), myvector.begin()+4);//(12 32 45 71)26 80 53 33

第二种使用:
自定义比较方法/类

The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
意思是:返回的参数用来确认形参第一个排不排在第二个前面:返回true表示形参的第一个排在第二个前面,反之在后面。

bool myfunction (int i,int j) { return (i<j); }

struct myclass {
  bool operator() (int i,int j) { return (i<j);}
} myobject;

// using function as comp
sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)

// using object as comp
sort (myvector.begin(), myvector.end(), myobject);//(12 26 32 33 45 53 71 80)

代码

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int cmp(string o1, string o2) 
{
    string sub1 = o1.substr(6, 8);//截取下标6字符及其以后共8个字符做新字符串
    string sub2 = o2.substr(6, 8);
    if(sub1 != sub2)
        return sub1 > sub2;//这样才能返回true时数字大在前
    else
        return o1 > o2;
}

int main() 
{
    int n;
    cin>>n;
    vector<string> str(n);
    for(int i=0;i<n;i++)
        cin >> str[i];
    sort(str.begin(),str.end(),cmp);
    for(int i=0;i<n;i++)
        cout << str[i] << endl;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值