您的位置:首页 >C++范围循环怎么用_基于范围的for详解
发布于2025-12-14 阅读(0)
扫一扫,手机访问
基于范围的for循环简化了容器和数组的遍历,语法为for (declaration : range),可避免手动管理迭代器。

在C++11中引入的基于范围的for循环(range-based for loop)是一种简洁、安全的方式来遍历容器或数组中的每个元素。它省去了手动管理迭代器或索引的麻烦,让代码更清晰易读。
range-based for循环的基本形式如下:
for (declaration : range) {
// 循环体
}
其中:
对C风格数组也可以直接使用range-based for:
int arr[] = {1, 2, 3, 4, 5};
for (int x : arr) {
std::cout << x << " ";
}
输出:1 2 3 4 5
这里x是每个元素的副本。如果不想拷贝,可以使用引用:
for (int& x : arr) {
x *= 2; // 修改原数组
}
对std::vector、std::list、std::string等容器,用法一致:
std::vector<std::string> words = {"hello", "world"};
for (const std::string& word : words) {
std::cout << word << "\n";
}
使用const std::string&避免字符串拷贝,提高效率。
使用range-based for时要注意以下几点:
begin()和end()的类。auto&)。示例:使用auto简化类型书写
std::map<std::string, int> scores = {{"Alice", 90}, {"Bob", 85}};
for (const auto& pair : scores) {
std::cout << pair.first << ": " << pair.second << "\n";
}
基本上就这些。掌握好基于范围的for循环,能让C++代码更现代、简洁、不易出错。
下一篇:Python合并字典的几种方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9