zoukankan      html  css  js  c++  java
  • STL之map

    map就是一種映射了,比如 map<string, int> m,就是string映射到int,m代表這個映射的數組,m[string] = int;

    映射完之後可以直接把string作為下標找到對應的int了!!!

    來一題:

    poj 2418.Hardwood Species

    本來還想連一下字典樹什麼的,原來可以有更簡單的方法,直接用map解決,這麼簡便的方法我怎麼好意思拒絕呢...

    注意一下題意,還有用printf輸出string的時候要加個c_str()轉換為c類型的字符串:

     1 // poj 2418.Hardwood Species
     2 // stl map
     3 // references:
     4 // http://www.cnblogs.com/rainydays/archive/2011/05/21/2052835.html
     5 #include <iostream>
     6 #include <cstdio>
     7 #include <cstring>
     8 #include <algorithm>
     9 #include <map>
    10 #include <string>
    11 
    12 using namespace std;
    13 
    14 const int N = 10005;    //species數量 
    15 
    16 string s;
    17 string species[N];
    18 map <string, int> m;
    19 
    20 int main()
    21 {
    22     int count = 0;
    23     int tot = 0;
    24     while(getline(cin, s) && s != "")
    25     {
    26         if(m[s] == 0)
    27         {
    28             species[count++] = s;
    29         }
    30         m[s]++;    
    31         tot++;    //注意最後除以總數,坑 
    32     }
    33     sort(species, species + count);
    34     for(int i=0; i<count; i++)
    35     {
    36         printf("%s %.4lf
    ", species[i].c_str(), m[species[i]] * 1.0 / tot * 100);    //string -> %s 要加上 c_str();
    37     }
    38 }
  • 相关阅读:
    危险无处不在 Html标签带来的安全隐患
    【转】服务器不支持FLV的解决办法
    IE8采用IE7模式
    解决IE中img.onload失效的方法
    字符串操作>静态串String
    装sql2005 express
    抽象类
    字符串操作>动态串StringBuilder
    使用数组
    集合>数组集合ArrayList
  • 原文地址:https://www.cnblogs.com/dominjune/p/4717403.html
Copyright © 2011-2022 走看看