C++如何使用范围for循环(range-based for)_C++ 范围for循环使用方法

c++11引入范围for循环,语法为for (declaration : expression),可简洁遍历数组或容器;支持普通数组、vector、Stringmap等具有begin()/end()的对象,通过引用可修改元素,用const引用避免拷贝;遍历map时元素为pair类型,推荐使用const auto&自动推导。

C++如何使用范围for循环(range-based for)_C++ 范围for循环使用方法

在C++11及以后的标准中,引入了范围for循环(range-based for loop),它提供了一种简洁、安全的方式来遍历容器或数组中的每一个元素。相比传统的for循环,范围for循环语法更清晰,不易出错。

基本语法

范围for循环的基本语法如下:

for (declaration : expression) {
    statement;
}

其中:

  • declaration:声明一个变量,用来接收当前遍历的元素。通常使用引用或const引用以避免拷贝。
  • expression:表示要遍历的序列,比如数组、vector、string、map等支持begin()和end()的容器。

遍历普通数组

对C风格数组也可以使用范围for循环:

立即学习C++免费学习笔记(深入)”;

int arr[] = {1, 2, 3, 4, 5};
for (int x : arr) {
    std::cout << x << ” “;
}
// 输出: 1 2 3 4 5

如果想修改数组元素,需要使用引用:

C++如何使用范围for循环(range-based for)_C++ 范围for循环使用方法

AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

C++如何使用范围for循环(range-based for)_C++ 范围for循环使用方法 56

查看详情 C++如何使用范围for循环(range-based for)_C++ 范围for循环使用方法

for (int& x : arr) {
    x *= 2; // 修改原数组
}

遍历标准容器(如vector、string)

对STL容器,用法同样简单:

std::vector<int> vec = {10, 20, 30};
for (const int& value : vec) {
    std::cout << value << ” “;
}
// 输出: 10 20 30

使用 const 引用可以避免不必要的拷贝,同时防止意外修改。

遍历map或unordered_map

map的每个元素是键值对(std::pair),所以要注意声明类型:

std::map<std::string, int> ages = {{“Alice”, 25}, {“Bob”, 30}};
for (const auto& pair : ages) {
    std::cout << pair.first << “: ” << pair.second << “n”;
}

使用 auto&const auto& 可自动推导pair类型,减少书写负担。

基本上就这些。只要对象有 begin() 和 end() 成员函数,或者可以用 ADL 找到对应的全局函数,就能用于范围for循环。常见类型包括数组、string、vector、list、set、map 等。

上一篇
下一篇
text=ZqhQzanResources