用法1
#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;
int main()
{
std::map<int, int> mapKeys;
mapKeys[1] = 1;
mapKeys[2] = 2;
mapKeys[3] = 3;
mapKeys[4] = 4;
for(auto it : mapKeys)
{
if(1 == it.first)
{
it.second = 5;
break;
}
}
for(auto it : mapKeys)
{
if(1 == it.first)
{
cout << it.second << endl;;
break;
}
}
return 0;
}
[root@localhost test]
1
"for(auto it : map)"方式不能修改迭代对象的值。
用法2
#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;
int main()
{
std::map<int, int> mapKeys;
mapKeys[1] = 1;
mapKeys[2] = 2;
mapKeys[3] = 3;
mapKeys[4] = 4;
for(auto &it : mapKeys) // 此处增加"&"
{
if(1 == it.first)
{
it.second = 5;
break;
}
}
for(auto it : mapKeys)
{
if(1 == it.first)
{
cout << it.second << endl;;
break;
}
}
return 0;
}
[root@localhost test]
5
"for(auto &it : map)"方式能修改迭代对象的值。