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

本文介绍了C++中遍历STL容器的传统方法,重点讲解了C++11引入的基于范围的for循环以及其优点,同时提到了在使用过程中需要注意的修改容器操作的限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

普通用法

在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循环虽然没显式看到迭代器,但是其实等价于使用迭代器遍历容器的值,我们在循环时修改容器对象,就会修改迭代器,导致后续的遍历的值都混乱了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Aries_Ro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值