問題描述
我有一個基于范圍的 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 循環修改地圖中的值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!