HDU-1004.Let the ballon Rise(STL-map)

2019-02-28-08:56:03

  初次做本题是用字符串硬钢,最近校队训练时又遇到才知道用map是真的舒服。需要注意的是map的用法。

  

      clear :

        清除map中的所有元素,map.clear();

      erase:

        删除 map 中指定位置的元素;map.erase(map.begin());

      insert :

        在 map 指定位置添加 pair 类型的元素;map.insert( pair< char, int >('f', 100) );

      begin, end :

        map 的正向迭代器的起始位置与终点位置;

      rbegin, rend :

        map 的反向迭代器的起始位置与终点位置;

      map.first    and     map.second可访问map的第一个和第二个元素。

map中元素的插入方式:

  方法一:pair

例:

  map<int, string> mp;
  mp.insert(pair<int,string>(1,"aaaaa"));

  方法二:make_pair
例:
  map<int, string> mp;
  mp.insert(make_pair<int,string>(2,"bbbbb"));

方法三:value_type
例:
  map<int, string> mp;
  mp.insert(map<int, string>::value_type(3,"ccccc"));

方法四:数组
例:
  map<int, string> mp;
  mp[4] = "ddddd";

  迭代器的申明方式:map<key_type, valye_type> :: iterator iter;
  需要注意的是,如果申明map<string, int >类型的变量,如果你只是插入string,则其对应的value默认为0,并在之后遇到相同的key值是可对其value值进行自增操作。

 1 #include <iostream>
 2 #include <map>
 3 using namespace std;
 4 
 5 map <string, int> ballon;
 6 
 7 int main () {
 8     int n;
 9     while(cin >> n && n) {
10         ballon.clear();
11         while(n --) {
12             string s;
13             cin >> s;
14             ballon[s] ++;
15         }
16         int max = 0;
17         string maxcolor;
18         map<string, int > ::iterator iter;
19         for(iter = ballon.begin(); iter != ballon.end(); iter ++) {
20             if(iter -> second > max) {
21                 max = (*iter).second;
22                 maxcolor = (*iter).first;
23             }
24         }
25         cout << maxcolor << endl;
26     }
27     return 0;
28 }
View Code
原文地址:https://www.cnblogs.com/bianjunting/p/10448266.html