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;
    }

     

  • 相关阅读:
    导出CSV乱码
    php让一个数组按照另外一个数组的键名进行排序
    电脑没有网
    Android抓包方法(转)
    封装curl的get和post请求
    JavaScript动态加载CSS和JS文件
    压缩视频之后网页上只有声音,没有图像
    php BCMath高精度计算
    非table结构数据导入excel
    如何将页面上的数据导入excel中
  • 原文地址:https://www.cnblogs.com/2020R/p/12443195.html
Copyright © 2011-2022 走看看