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;
}
运行结果:

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

被折叠的 条评论
为什么被折叠?



