输入若干个整数,当输入0时表示结束,统计每个输入整数的出现次数。

本文介绍了一种使用C++中的map容器来统计一系列输入整数出现频率的方法。通过不断读取用户输入直到遇到0为止,程序能够有效地追踪并输出每个不同整数的出现次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【描述】
输入若干个整数,当输入0时表示结束,统计每个输入整数的出现次数。
【输入】
输入若干个整数,整数之间以空格间隔,当输入0时表示结束。
【输出】
分行输出每个整数出现的次数。行末不能有多余空格。
【输入示例】
11 22 35 68 97 63 22 68 11 0
【输出示例】
11: 2
22: 2
35: 1
63: 1
68: 2
97: 1
【提示】
可以使用map来保存二元组<输入整数,出现次数>。

#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
#include<cctype>
#include<iomanip>
#include<cmath>
#include<cstdlib>
#include<vector> 
#include<deque>
#include<list> 
#include<set> 
#include<iterator>
#include<map> 
using namespace std;
int main(){
    int n,count=0;
    map<int,int>m;          
    while(cin>>n){
        if(n==0)
            break;
        map<int,int>::iterator p;
        p=m.find(n);      //用于查找相同的元素
        if(p==m.end())
            m.insert(pair<int,int>(n,1));   //如果没有,则新建二元组
        else{
            count=m.find(n)->second;       //成功,记录次数
            m.erase(n);                    //删除原来的二元组
            m.insert(pair<int,int>(n,++count));
        }
    }
    for(auto pos=m.begin();pos!=m.end();++pos)
        cout<<pos->first<<": "<<pos->second<<endl;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值