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
注意:这种写法不能获取数组索引,只适合只需要元素值的场景。
如果容器中存储的是大对象(如 string、自定义类等),直接用值会引发不必要的拷贝。应该使用引用:
std::vector<std::string> words = {"hello", "world", "cpp"};
for (const std::string& word : words) {
std::cout << word << std::endl;
}
以下容器都支持范围 for 循环:
示例:遍历 map
std::map<int, std::string> m = {{1, "one"}, {2, "two"}};
for (const auto& pair : m) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
基本上就这些。C++11 的范围 for 让代码更清晰,推荐在能用的地方优先使用。
以上就是c++++ for range循环 c++11范围for循环教程的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号