C++map对key进行排序//PAT统计字符串数字个数

L1-003 个位数统计 (15 分)ios

给定一个 k 位整数 N=d​k−1​​10​k−1​​+⋯+d​1​​10​1​​+d​0​​ (0≤d​i​​≤9, i=0,⋯,k−1, d​k−1​​>0),请编写程序统计每种不一样的个位数字出现的次数。例如:给定 N=100311,则有 2 个 0,3 个 1,和 1 个 3。函数

输入格式:

每一个输入包含 1 个测试用例,即一个不超过 1000 位的正整数 N。测试

输出格式:

对 N 中每一种不一样的个位数字,以 D:M 的格式在一行中输出该位数字 D 及其在 N 中出现的次数 M。要求按 D 的升序输出。spa

输入样例:

100311

输出样例:

0:2
1:3
3:1

map的key默认的对string类,int,char 有排序功能,也能够根据须要本身写比较函数code

#include<iostream>
#include<cstdlib>
#include<map>
#include<string>
using namespace std;
struct cmp{     //注意,这里只是对key排序这样用
    bool operator()(const char &s1,const char &s2){ 
         return s1>s2;  //别忘记operator后面的'()'
    }
};
int main(){
    string s;
    int i;
    while(cin>>s){
        int n=s.length();
        map<char,int,cmp> m;   //
        for(i=0;i<n;i++){
            m[s[i]]++;
        }
        map<char,int,cmp>::iterator it=m.begin(); //
        for(;it!=m.end();it++){
            cout<<it->first<<":"<<it->second<<endl;
        }
    }
    system("pause");
    return 0;
}