How can I modify values in a map using range based for loop?(如何使用基于范围的 for 循环修改地图中的值?)
问题描述
我有一个基于范围的 for 循环来迭代 foobar 中的元素,如下所示:
#include此代码产生以下输出:
{1, 2} {2, 3} {3, 4}{1, 1} {2, 2} {3, 3}第一行被修改并打印在 for 循环中,第二行应该打印相同的修改值.为什么输出不匹配?对
std::map的更改是否仅在循环范围内有效?有没有办法不仅可以访问而且可以修改这些值?可以在 cpp.sh 上找到 此代码的运行版本.
为了清楚起见,此处给出的示例经过修改以匹配接受的答案.
解决方案你可以把
auto变成auto&如果你想改变/修改容器,例如:#include编译和输出
<前>{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
这篇关于如何使用基于范围的 for 循环修改地图中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用基于范围的 for 循环修改地图中的值?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
