利用map可以统计元素个数,下面主要介绍这三种方法:
1、利用find函数统计每一个元素出现的次数
void test_map2()
{
string strs[] = { "苹果", "香蕉", "草莓", "苹果", "香蕉", "香蕉", "香蕉", "苹果", "香蕉", "草莓" };
map<string, int> countmap;
//利用find统计每一个元素出现的次数
for (const auto& e : strs)
{
map<string, int>::iterator it = countmap.find(e);
//countmap.end()是map中最后一个元素的下一个
if (it != countmap.end())
{
//如果找到,value++;
it->second++;
}
else
{
//若是没有再去插入,又要遍历一遍,有些许冗余
countmap.insert(make_pair(e, 1));
}
}
//遍历每一个元素
map<string, int>::iterator cit = countmap.begin();
while (cit != countmap.end())
{
cout << cit->first << ":" << cit->second << endl;
cit++;
}
}
2、利用insert统计每个元素出现的次数
void test_map3()
{
string strs[] = { "苹果", "香蕉", "草莓", "苹果", "香蕉", "香蕉", "香蕉", "苹果", "香蕉", "草莓" };
map<string, int> countmap;
//pair<iterator,bool> insert (const value_type& val);
//此类型的insert返回值是一个pair,第一个元素first是一个迭代器,指向新插入元素的map,第二个元素second是一个bool值,插入成功返回true,否则返回false
for (const auto& e : strs)
{
std::pair<std::map<std::string, int>::iterator, bool> ret = countmap.insert(make_pair(e, 1));
if (ret.second == false)
{
ret.first->second++;
}
}
map<string, int>::iterator cit = countmap.begin();
while (cit != countmap.end())
{
cout << cit->first << ":" << cit->second << endl;
cit++;
}
}
3、利用operator[ ]统计每个元素出现的次数
void test_map4()
{
string strs[] = { "苹果", "香蕉", "草莓", "苹果", "香蕉", "香蕉", "香蕉", "苹果", "香蕉", "草莓" };
map<string, int> countmap;
for (const auto& e : strs)
{
//先调用operator[];再对返回值value进行++。
countmap[e]++;
}
for (auto& e : countmap)
{
cout << e.first << ":" << e.second << endl;
}
}
以上三种方式的输出结果:
若有童鞋不明白利用operator[ ]统计次数的方式,可参见博客https://blog.csdn.net/yam_sunshine/article/details/89930311
里面有详细介绍operator[ ]的用法及其原理。