zoukankan      html  css  js  c++  java
  • 7-24 树种统计 (25分)-map

    没有学过C++的STL,也没有用过map,基本上是把别人代码照抄一遍。

    参考链接:

     定义一个map:

    map<string, int> tree

    find()函数返回的是一个迭代器,如果没有要查找的结构,则指向end(),可以通过tree[name]来访问具体元素

     if (tree.find(name) == tree.end())
         {
             tree[name] = 1;
         }
            else
         {
             tree[name]++;
         }

    定义一个迭代器(游标)it,用来遍历map

    map<string, int>::iterator it;

    for循环中it刚开始指向map的第一个元素,每次递增1位,当指向end()时结束循环

    用(*it)访问map中的元素

       for (it = tree.begin(); it != tree.end(); it++)
        {
            double perc = (*it).second*1.0 / N * 100;
            if (it == tree.end())
            {
                cout << (*it).first << " " << fixed << setprecision(4) << perc << '%';
            }
            else
                cout << (*it).first << " " << fixed << setprecision(4) << perc << '%' <<endl;
        }
    #include <iostream>
    #include <string>
    #include <cstring>
    #include <map>
    #include<iomanip>
    using namespace std;
    int main()
    {
        int N;
        map<string, int> tree;
        cin >> N;
        getchar();//原文也提醒了,不加getchar()不能通过,因为第一个接收的字符串为空了
        string name;
        for (int i = 0; i < N; i++)
        {
            getline(cin, name);
              if (tree.find(name) == tree.end())
                {
                    tree[name] = 1;
                }
                else
                {
                    tree[name]++;
                }
        }
        map<string, int>::iterator it;
        for (it = tree.begin(); it != tree.end(); it++)
        {
            double perc = (*it).second*1.0 / N * 100;
            if (it == tree.end())
            {
                cout << (*it).first << " " << fixed << setprecision(4) << perc << '%';
            }
            else
                cout << (*it).first << " " << fixed << setprecision(4) << perc << '%' <<endl;
        }
        return 0;
    }

     

  • 相关阅读:
    洛谷P2894 [USACO08FEB]酒店Hotel
    codevs 3981 动态最大子段和
    舞蹈家怀特先生(线型)
    IOS8 通知中心(Notification Center)新特性
    WWDC2014 IOS8 APP Extensions
    IOS8 TouchID使用介绍
    IOS8 UIAlertController 弹框
    Unable to run Kiwi tests on iOS8 device
    registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later
    iOS开发---- 开发错误汇总及解决方法
  • 原文地址:https://www.cnblogs.com/2020R/p/12443195.html
Copyright © 2011-2022 走看看