c++ for循环中使用auto关键字

用法1

  • 代码
#include 
#include 
#include 
using namespace std;

int main()
{
	std::map 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]# ./testAuto
1
  • 总结
"for(auto it : map)"方式不能修改迭代对象的值。

用法2

  • 代码
#include 
#include 
#include 
using namespace std;

int main()
{
	std::map 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]# ./testAuto
5
  • 总结
"for(auto &it : map)"方式能修改迭代对象的值。

你可能感兴趣的:(c++,c++,c++11)