范围for循环简化容器遍历,语法为for (declaration : expression),适用于读取或修改元素、无需索引的全容器遍历,推荐使用const引用避免拷贝,但不适用于需索引、部分遍历或删除元素等场景。

在C++11及以后的标准中,引入了范围for循环(range-based for loop),它极大地简化了容器和数组的遍历操作。相比传统的for循环,范围for语法更简洁、易读,也减少了出错的可能性。
范围for循环的基本形式如下:
for (declaration : expression) {
// 循环体
}
其中:
编译器会自动迭代expression中的每一个元素,并将其赋值给declaration。
立即学习“C++免费学习笔记(深入)”;
以下是一些典型的应用场景和写法:
遍历std::vector并读取元素
#include <vector>
#include <iostream>
std::vector<int> nums = {1, 2, 3, 4, 5};
for (int n : nums) {
std::cout << n << " ";
}
// 输出:1 2 3 4 5
使用引用避免拷贝(推荐修改或大对象)
std::vector<std::string> words = {"hello", "world"};
for (const std::string& word : words) { // 只读,用const引用
std::cout << word << " ";
}
for (std::string& word : words) { // 修改内容
word += "!";
}
对复杂类型(如string、class对象),使用引用可以避免不必要的拷贝,提升性能。
遍历C风格数组
int arr[] = {10, 20, 30};
for (int x : arr) {
std::cout << x << " ";
}
只要编译器能推断出数组大小,就可以使用范围for。
遍历std::map
#include <map>
std::map<std::string, int> ages = {{"Alice", 25}, {"Bob", 30}};
for (const auto& pair : ages) {
std::cout << pair.first << ": " << pair.second << "\n";
}
注意map的元素是std::pair类型,因此要通过.first和.second访问键值。
范围for循环适合大多数“顺序访问所有元素”的情况,但也有局限性:
适合的场景:
不适合的场景:
例如,无法直接用范围for实现删除操作:
std::vector<int> v = {1, 2, 3, 4};
for (auto it = v.begin(); it != v.end(); ) {
if (*it % 2 == 0) it = v.erase(it);
else ++it;
}
这种情形仍需传统迭代器方式。
基本上就这些。范围for循环让C++的遍历变得更像Python或Java,写起来干净利落,只要注意使用引用和理解其限制,就能高效安全地使用。不复杂但容易忽略细节。
以上就是c++++如何使用范围for循环_C++简化遍历语法与使用场景的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号