Statistic length of service (20 points) (one trick on map)

Given the length of service of N employees in a company, it is required to output the number of employees in each length of service in increasing order of service age.

Input format:
Input firstly give a positive integer N (≤10​5), which is the total number of employees; then give N integers, that is, the length of service of each employee, in the range [0, 50].

Output format:
output the number of employees of each service age in increasing order of service age, the format is: "service age: number of people". Each item occupies one line. If the number of people is 0, the item is not output.

Input sample:

8
10 2 0 5 7 2 5 2

Sample output:

0:1
2:3
5:2
7:1
10:1

This question is output in ascending order of service, directly map, the keys are not repeated and the key values ​​in the map are sorted from small to large, and the sorting is done directly. However, I use C++ to write this data structure exercise. The final exam is very good. . . .
#include <iostream> 
#include <algorithm>
#include <map>
using namespace std;

int main(){
    
    
	ios::sync_with_stdio(false);
	cin.tie(0),cout.tie(0);
	map<int,int> m;
	int n,age;
	cin >> n;
	for(int i = 0;i<n;i++){
    
    
		cin >> age;
		m[age]++;
	}
	for(auto it = m.begin();it!=m.end();it++){
    
    
		if(it->second>0){
    
    
			cout << it->first << ":" << it->second << endl;
		}
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45845039/article/details/108743625