C++11实用技术(四)for循环该怎么写

普通用法

在C++遍历stl容器的方法通常是:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
    1, 2, 3};
	for (auto it = arr.begin(); it != arr.end(); ++it)
	{
    
    
		std::cout << *it << std::endl;
	}
	return 0;
}

上述代码需要关注迭代器,也需要显示得给出容器的begin和end。不便于书写。C++11支持基于范围的for循环。如下

C++11基于范围的for循环

C++11基于范围的for循环如下所示:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
    1, 2, 3};
	for (auto n : arr)
	{
    
    
		std::cout << n << std::endl;
	}
	return 0;
}

还可以使用引用修改容器的值:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
    1, 2, 3};
	for (auto& n : arr)
	{
    
    
		n++;
	}
	//n的值为2,3,4
	return 0;
}

map容器也支持:

#include <iostream>
#include <map>
#include <string>

int main() {
    
    
	std::map<std::string, int> mp = {
    
     {
    
    "1",1}, {
    
    "2", 2}, {
    
    "3", 3} };
	for (auto& n : mp)
	{
    
    
		std::cout << n.first << " -> " << n.second << std::endl;
	}
	return 0;
}

注意

但基于范围的for循环,在循环时不支持修改容器:
例如:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
     1, 2, 3 };
	for (auto n : arr)
	{
    
    
		std::cout << n << std::endl;
		arr.push_back(4);//修改arr
	}
	return 0;
}

运行结果:
在这里插入图片描述
主要原因是上面for循环虽然没显式看到迭代器,但是其实等价于使用迭代器遍历容器的值,我们在循环时修改容器对象,就会修改迭代器,导致后续的遍历的值都混乱了。

猜你喜欢

转载自blog.csdn.net/weixin_44477424/article/details/132307271