c++ - 如何增加地图中的前一个值?
问题描述
我在 C++ 中使用 std::map 数据结构,并且每次都尝试在某个位置增加值。
如果我了解它map
有一个键和一个与该特定键关联的值。
所以我正在迭代一个array
存储在他内部的唯一整数。
我试图做的是,当我遍历数组时,将存储在数组的特定索引中的值作为键传递给我的地图。
例如:
std::map<int, int> my_map;
for(int i = 0; i < array.size(); ++i)
{
my_map.insert(array[i], ...); // the ... part is supposed to be the increment
}
我想通过++my_map[array[i]]
。我没有尝试过,因为我目前无法访问我的笔记本电脑。这只是我不在家时想出的一个想法,我想问一下。
如果my_map[array[i]]
是有效的,我想在我的循环中使用它作为 if 语句:
std::map<int, int> my_map;
for(int i = 0; i < array.size(); ++i)
{
// set the initial value to 0 if the element doesn't exist in the map
// else increment the previous value by one
if(!my_map.find(array[i]))
{
my_map.insert(array[i], 0);
}
else
{
my_map.insert(array[i], ++my_map[array[i]]);
}
}
如果我脑子有问题,请纠正我。我希望我将我的问题翻译得足够好,以便您理解。谢谢你们!
编辑:正如我在评论中所说,正确的代码是:
for(int i = 0; i < array.size(); ++i)
{
// set the initial value to 0 if the element doesn't exist in the map
// else increment the previous value by one
if(!(my_map.count(array[i])))
{
my_map.insert(std::pair<int,int>(array[i], 0));
}
else
{
my_map.insert(std::pair<int,int>(array[i], ++my_map[array[i]]));
}
}
再次谢谢大家!!!
解决方案
if(my_map.find(array[i])==my_map.end()){//YOU CAN ALSO USE stl function count
my_map.insert(make_pair(array[i], 0));
}else{
my_map.insert(make_pair(array[i], ++my_map[array[i]]));
}
OR:
if(my_map.find(array[i])==my_map.end()){
my_map[array[i]]=0;
}else{
my_map[arr[i]]++;
}
推荐阅读
- r - 悬停在绘图上时在工具提示上显示所有值
- java - 如何使用 Java 11 捆绑和启动本机 Mac/Windows 应用程序?
- java - “续订至”的 Kerberos 自动更新
- c# - Bootstrap Checkbox-我如何返回输入的值?
- angular - 如何在 Angular i18n 路由器模块中使用 LOCALE_ID
- php - 转移网站后 - PHP 致命错误:允许的内存大小为 41943040 字节已用尽(尝试分配 32768 字节)
- scala - 在 Scala 中具有函数的半群
- d3.js - D3 join 的关键功能显然没有效果
- postgresql - TypeORM postgresql 急切加载关系定义为惰性
- python - 随机森林不预测零