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

     

  • 相关阅读:
    Java基础加强总结(一)——注解(Annotation)
    修改intellij(idea)中mybatis对应的xml背景颜色
    spring 手动添加 bean 到容器,例子 :多数据源配置
    Quartz使用总结
    js 上一步 下一步 操作
    BigDecimal提供了8种舍入方式
    precision scale
    jQuery jsonp跨域请求
    js菜鸟进阶-jQuery源码分析(1)-基本架构
    逐行分析jQuery源码
  • 原文地址:https://www.cnblogs.com/2020R/p/12443195.html
Copyright © 2011-2022 走看看