我想要一张CStrings的地图,并将它们计数成映射对。
例如,如果我有:
"Banana",
"Banana",
"Apple",
"Apple",
"Pear"我想要("Banana", 2), ("Apple", 2), ("Pear", 1)。
int sortFruit (std::map<CString, int> &mapFruitTypes)
{
for (const auto& a : someArray)
{
CString fruitType = a -> GetFruitType();
int i = 0;
mapFruitTypes.emplace(fruitType , i++);
}
return 0;
}这样做对吗?或者我应该使用其他的东西(而不是emplace )?
发布于 2020-04-17 08:35:58
当您看到每个水果类型时,您可以简单地增加地图的值。当使用[]访问映射的值时,它会被插入,并且值也是值--对于类型初始化(因此值得到0 --用于int类型)。
因此,这就足够了(无论是插入新键还是计算它们):
for (const auto& a : someArray)
{
CString fruitType = a -> GetFruitType();
mapFruitTypes[fruitType]++;
}发布于 2020-04-17 08:44:39
基本上有三种方法可以将键映射到当前的键计数。
方法1:
使用std::map::operator[]
int sortFruit (std::map<CString, int> &mapFruitTypes)
{
for (const auto& a : someArray)
mapFruitTypes[a->GetFruitType()]++;
return 0;
}方法2:
使用std::map::插入方法,并利用返回值(即std::pair<iterator, bool>),其中iterator是插入项的迭代器,如果键已经存在,则使用现有项。
int sortFruit (std::map<CString, int> &mapFruitTypes)
{
for (const auto& a : someArray)
mapFruitTypes.insert({a->GetFruitType(), 0}).first->second++;
return 0;
}方法3:
使用std::map::emplace方法,并利用返回值,类似于方法2:
int sortFruit (std::map<CString, int> &mapFruitTypes)
{
for (const auto& a : someArray)
mapFruitTypes.emplace(a->GetFruitType(), 0).first->second++;
return 0;
}https://stackoverflow.com/questions/61266707
复制相似问题