C++ : 应用map统计水果的个数

该博客主要介绍了使用C++的map来统计水果个数,通过特定代码实现此功能并展示了运行结果,体现了C++在数据统计方面的应用。

C++ : 应用map统计水果的个数

#include <iostream>
#include <string>

using namespace std;

//左子树的所有值小于根节点,右子树的所有值大于根节点
#include <map>

void test_map()
{
//统计水果出现的次数
    std::string strs[] = { "苹果", "苹果", "香蕉", "桃子", "香蕉", "桃子", "西瓜", "苹果" };

    typedef std::map<std::string, int> CountMap;
    typedef std::map<std::string, int>::iterator CountMapIter;

    std::map<std::string, int> countmap;
    //for (const std::string& str : strs)
    for (const auto& str : strs) //表示找到了,数量增加
    {
        //std::pair<std::map<std::string, int>::iterator, bool> ret = countmap.insert(make_pair(str, 1));
        //auto ret = countmap.insert(make_pair(str, 1));   //可读性差
        std::pair<CountMapIter, bool> ret = countmap.insert(make_pair(str, 1));
        if (ret.second == false)
        {
            ret.first->second++;
        }
    }
//<法一>
    //std::map<std::string, int>::iterator cit = countmap.begin();
    auto cit = countmap.begin(); //简写
    while (cit != countmap.end())
    {
        cout << cit->first << ":" << cit->second << endl;
        ++cit;
    }
    cout << endl;
    
//*********************************************************************
//<法二>
    for (const auto& kv : countmap)  //写for时一定要带上const &,除非是遍历int类型的东西(拷引用再赋值,不影响);把countmap里的数据拿出来
    {
        cout << kv.first << ":" << kv.second << endl;
    }

    cout << endl;
}


int main()
{
    test_map();
    system("pause");
    return 0;
}

运行结果:
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值