简介

Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据 处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。我理解相当于python中的字典,弥补了c++没有集合数据类型的缺陷

使用map

使用map要包含map类所在的头文件
#include <map> //注意,STL头文件没有扩展名.h
map对象是模板类,需要关键字和存储对象两个模板参数:
std:map<string, int> Ballon;

hdu1004

Problem Description
Contest time again! How excited it is to see balloons floating around. But to tell you a secret, the >judges' favorite time is guessing the most popular problem. When the contest is over, they will count >the balloons of each color and find the result.
This year, they decide to leave this lovely job to you.
Input
Input contains multiple test cases. Each test case starts with a number N (0 < N <= 1000) -- the >total number of balloons distributed. The next N lines contain one color each. The color of a balloon >is a string of up to 15 lower-case letters.
A test case with N = 0 terminates the input and this test case is not to be processed.
Output
For each case, print the color of balloon for the most popular problem on a single line. It is >guaranteed that there is a unique solution for each test case.
Sample Input
5
green
red
blue
red
red
3
pink
orange
pink
0
Sample Output
red
pink

AC代码

#include <iostream>
#include <string>
#include <map>
using namespace std;

int main(){
    map<string, int> Ballon;
    string color, MaxColor;
    int n, max;
    while(cin>>n&&n){
        Ballon.clear();
        while(n--){
            cin>>color;
            Ballon[color]++;
        }
        map<string, int>::iterator it;
        max = 0;
        for(it=Ballon.begin(); it!=Ballon.end(); it++){
            if(it->second>max){
                max = it->second;
                MaxColor = it->first;
            }
        }
        cout<<MaxColor<<endl;
    }
    return 0;

标签: c++, oj

仅有一条评论

  1. 我把你的文章读完了。发现身边的大佬 ╰(*°▽°*)╯,求带~~~

添加新评论