map结合pair排序介绍及例题

本文介绍了如何在C++中利用map和pair对数据进行统计和排序,包括按照key值升序和降序,以及按照value值降序排序的方法,并通过一个PAT1054TheDominantColor的例题展示了具体应用。
摘要由CSDN通过智能技术生成

基础知识

map和pair的介绍

以下代码的输入均为5*3共15个数字

5 3
0 0 2 1 24
24 24 0 0 24
24 0 24 24 24
  1. map默认按照key值升序排序
#include <bits/stdc++.h>

using namespace std;

map<int,int>color;

int main(){
    int n,m;
    cin>>m>>n;
    int k=m*n;
    while(k--)
    {
        int x;
        cin>>x;
        color[x]++;
    }
    map<int,int>::iterator it;
    for(it=color.begin();it!=color.end();it++)
        cout<<it->first<<"--->"<<it->second<<endl;
    return 0;
}
//输出结果为
0--->5
1--->1
2--->1
24--->8
  1. 使用sort函数按key降序排列,需要借助vector和pair
#include <bits/stdc++.h>

using namespace std;

map<int,int>color;
typedef pair<int ,int>PAIR;
int cmp(PAIR a,PAIR b)
{
    return a.first>b.first;
}
int main(){

    int n,m;
    cin>>m>>n;
    int k=m*n;
    while(k--)
    {
        int x;
        cin>>x;
        color[x]++;
    }
    map<int,int>::iterator it;
    vector<PAIR> vec(color.begin(),color.end());
    sort(vec.begin(),vec.end(),cmp);
    for(int i=0;i<vec.size();i++)
        cout<<vec[i].first<<"--->"<<vec[i].second<<endl;

    return 0;
}
//output:
24--->8
2--->1
1--->1
0--->5
  1. 按value值进行降序排序
//只需将2中的cmp函数中的first改为second
int cmp(PAIR a,PAIR b)
{
    return a.second>b.second;
}
//output
24--->8
0--->5
1--->1
2--->1
  1. 取消和替换sort排序
    懒了,直接搬运

例题

1.PAT 1054 The Dominant Color (20分)

  1. 题目:PAT 1054 The Dominant Color (20分)
  2. 思路:map+pair。用map<int, int>记录每个数出现的次数,然后放入vector容器中按value值从大到小排序,最后输出最大的value值对应的key值
  3. AC代码
#include <bits/stdc++.h>

using namespace std;

map<int,int>color;
typedef pair<int ,int>PAIR;

int cmp(PAIR a,PAIR b)
{
    return a.second>b.second;
}

int main(){
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif

    int n,m;
    cin>>m>>n;
    int k=m*n;
    while(k--)
    {
        int x;
        cin>>x;
        color[x]++;
    }
    vector<PAIR> vec(color.begin(),color.end());
    sort(vec.begin(),vec.end(),cmp);
    cout<<vec[0].first;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值