首页 > 解决方案 > 如何增加地图中的前一个值?

问题描述

我在 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]]));
    }
}

再次谢谢大家!!!

标签: c++c++11

解决方案


  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]]++;
   }

推荐阅读