如何使用基于循环的范围修改地图中的值? [英] How can I modify values in a map using range based for loop?

查看:118
本文介绍了如何使用基于循环的范围修改地图中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于范围的for循环遍历 foobar 中的元素如下:

  #include< map> 
#include< iostream>

int main()
{
std :: map< int,int> foob​​ar({{1,1},{2,2},{3,3}});

for(auto p:foobar)
{
++ p.second;
std :: cout<< {<< p.first<< ,< p.second<< };
}
std :: cout<< std :: endl;

for(auto q:foobar)
{
std :: cout< {<< q.first<< ,< q.second<< };
}
std :: cout<< std :: endl;
}

此代码生成以下输出:

  {1,2} {2,3} {3,4} 
{1,1} {2,2} {3,3} b $ b

第一行被修改并打印在for循环中,第二行打印相同的修改值。为什么输出不匹配?对 std :: map 的更改是否只在循环范围内有效?是否有一种方法我不能只访问但修改这些值?



A EDIT:此处给出的示例已修改为匹配,可以在cpp.sh上找到此代码的运行版本

您可以将 auto 变成

code> auto&
如果您要变更/修改容器,例如:

  #include< map> 
#include< iostream>

int main()
{
std :: map< int,int> foob​​ar({{1,1},{2,2},{3,3}});
for(auto& p:foobar){
++ p.second;
std :: cout<< '{'<< p.first<< ,< p.second<< };
}
std :: cout<< std :: endl;
}

编译和输出

 
{1,2} {2,3} {3,4}

实例


I have a range based for loop to iterate over elements in foobar as follows:

#include <map>
#include <iostream>

int main()
{
  std::map<int, int> foobar({{1,1}, {2,2}, {3,3}});

  for(auto p : foobar) 
  {
    ++p.second;
    std::cout << "{" << p.first << ", " << p.second << "} ";
  }
  std::cout << std::endl;

  for(auto q : foobar) 
  {
    std::cout << "{" << q.first << ", " << q.second << "} ";
  } 
  std::cout << std::endl;
}

This code produces the following output:

{1, 2} {2, 3} {3, 4}
{1, 1} {2, 2} {3, 3}

The first line is modified and printed inside a for loop and the second line supposedly prints the same modified values. Why don't the outputs match? Are changes to std::map only effective in the scope of the loop? Is there a way I can not only access but modify these values?

A running version of this code can be found on cpp.sh.

EDIT: The example given here was modified to match the accepted answer for clarity.

解决方案

You can turn auto into auto& if you want to mutate/modify the container, for instance:

#include <map>
#include <iostream>

int main()
{
  std::map<int, int> foobar({{1,1}, {2,2}, {3,3}});
  for(auto& p : foobar) {
    ++p.second;
    std::cout << '{' << p.first << ", " << p.second << "} ";
  }
  std::cout << std::endl;
}

compiles ands outputs

{1, 2} {2, 3} {3, 4} 

live example

这篇关于如何使用基于循环的范围修改地图中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆