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

     

  • 相关阅读:
    利用docker搭建测试环境--安装
    fiddler获取手机请求
    python多线程
    linux下安装python的第三方module
    shell编程sed笔记
    shell 函数
    mysql information_schema 数据库简介:
    shell常用的判断条件
    gulp:gulp-sass基础教程
    (六):关于全局config配置
  • 原文地址:https://www.cnblogs.com/2020R/p/12443195.html
Copyright © 2011-2022 走看看