C++11引入范围for循环,语法为for (declaration : range),可简洁遍历容器或数组元素,避免手动管理迭代器。

在C++11及以后的标准中,引入了范围for循环(range-based for loop),它提供了一种简洁的方式来遍历容器或数组中的每一个元素,而不需要手动管理迭代器或下标。
范围for循环的基本语法如下:
for (declaration : range) {
// 循环体
}
其中:
下面通过几个例子说明如何使用范围for循环:
立即学习“C++免费学习笔记(深入)”;
遍历并读取数组元素:
int arr[] = {1, 2, 3, 4, 5};
for (int x : arr) {
std::cout << x << " ";
}
输出:1 2 3 4 5
使用引用修改容器中的元素:
std::vector<int> vec = {10, 20, 30};
for (int& x : vec) {
x += 5; // 修改原容器中的值
}
// 此时vec为{15, 25, 35}
使用const引用避免拷贝且防止修改:
std::vector<std::string> words = {"hello", "world"};
for (const std::string& word : words) {
std::cout << word << "\n";
}
遍历字符串中的字符:
std::string str = "cpp";
for (char c : str) {
std::cout << c << " ";
}
输出:c p p
使用范围for循环时需要注意以下几点:
基本上就这些。范围for循环让代码更清晰、安全,适合大多数顺序遍历场景。
以上就是c++++中范围for循环(range-based for)怎么用_c++范围for循环语法说明的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号