zoukankan      html  css  js  c++  java
  • STL之map排序

    描述

    STL的map中存储了字符串以及对应出现的次数,请分别根据字符串顺序从小到大排序和出现次数从小到大排序。

    部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码。

    int main()
    {
        map<string, int> sm;
        int n;
        cin>>n;
        while(n--)
        {
            string s;
            int x;
            cin>>s>>x;
            sm[s] = x;
        }
        SortOutput(sm);
        return 0;
    }

    输入 

    输入数据第一行为正整数n,接下来包含n行,每行一个字符串和出现的次数。

    所有字符串和次数均不相同。

    输出

    分别按照字符串和出现次数排序,并输出map中的键和值,每行一对。

    样例输入

     5
    abc 1
    bcd 3
    cde 2
    def 5
    efg 4

    样例输出

     abc 1
    bcd 3
    cde 2
    def 5
    efg 4
    abc 1
    cde 2
    bcd 3
    efg 4
    def 5

    今天做训练赛的时候知道一道题要用map,就是不会,回来仔细学了map,它的键-值对应的关系方便解决一对一的数据,很是nice

    #include <string>
    #include <iostream>
    #include <vector>
    #include <map>
    #include<algorithm>
    using namespace std;
    void SortOutput(map<string,int>&sm)
    {
        map<string,int >::iterator it;
        vector<int> v;
        for(it=sm.begin();it!=sm.end();++it)
        {
            cout<<it->first<<" "<<it->second<<endl;//map内部默认升序排序,不能用sort
            v.push_back(it->second);
        }
        sort(v.begin(),v.end(),less<int>());//默认降序,升序用greater<int>();
        int n;
        for(int i=0;i<v.size();i++)
        {
            map<string,int>::iterator it;
            for(it=sm.begin();it!=sm.end();it++)
            {
                if(v[i]==it->second)
                {
                    cout<<it->first<<" "<<it->second<<endl;//it->first访问键,it->second访问值
                }
            }
        }
    }
    int main()
    {
        map<string, int> sm;
        int n;
        cin>>n;
        while(n--)
        {
            string s;
            int x;
            cin>>s>>x;
            sm[s] = x;
        }
        SortOutput(sm);
        return 0;
    }

     

  • 相关阅读:
    java中getResourceAsStream的问题 缓存
    springside 查询条件
    如何修改MySQL数据库引擎为INNODB
    获取用户真实 IP , 淘宝IP接口获得ip地理位置
    hibernate注解的CascadeType属性
    AssignmentHandler实现类用spring注入
    使用 jQuery dataTables
    转载:一致性 hash 算法( consistent hashing )
    转载:memcached完全剖析
    转载:连接MySQL数据库的两种方式介绍
  • 原文地址:https://www.cnblogs.com/andrew3/p/8835970.html
Copyright © 2011-2022 走看看