【现代C++】范围基于的for循环

在这里插入图片描述

现代C++中的范围基于的for循环(range-based for loop)是C++11引入的一项特性,旨在简化对容器或范围的迭代过程。这种循环语法不仅使代码更清晰易读,还减少了迭代时的错误。以下是范围基于的for循环的详细介绍:

1. 基本用法

范围基于的for循环可以遍历任何提供迭代器的容器。

#include <vector>
#include <iostream>

void basicExample() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (int num : vec) {
        std::cout << num << " ";
    }
    // 输出: 1 2 3 4 5
}

2. 使用引用遍历

为了避免在迭代时复制元素,可以使用引用。

#include <vector>
#include <iostream>

void referenceExample() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for (int& num : vec) {
        num *= 2; // 修改元素
    }

    for (const int& num : vec) {
        std::cout << num << " "; // 读取元素
    }
    // 输出: 2 4 6 8 10
}

3. 遍历数组

范围基于的for循环也可以用于遍历数组。

#include <iostream>

void arrayExample() {
    int arr[] = {1, 2, 3, 4, 5};
    for (int num : arr) {
        std::cout << num << " ";
    }
    // 输出: 1 2 3 4 5
}

4. 遍历字符串

可以使用范围基于的for循环遍历字符串中的每个字符。

#include <iostream>
#include <string>

void stringExample() {
    std::string str = "hello";
    for (char ch : str) {
        std::cout << ch << " ";
    }
    // 输出: h e l l o
}

5. 遍历映射(Map)

遍历std::mapstd::unordered_map时,可以获取每个键值对。

#include <map>
#include <iostream>

void mapExample() {
    std::map<std::string, int> wordCount = {{"apple", 1}, {"banana", 2}, {"cherry", 3}};
    for (const auto& pair : wordCount) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }
    // 输出:
    // apple: 1
    // banana: 2
    // cherry: 3
}

6. 结合自动类型推导(auto)

使用auto关键字可以让编译器自动推断元素的类型,进一步简化代码。

#include <vector>
#include <iostream>

void autoExample() {
    std::vector<double> vec = {1.1, 2.2, 3.3, 4.4, 5.5};
    for (auto num : vec) {
        std::cout << num << " ";
    }
    // 输出: 1.1 2.2 3.3 4.4 5.5
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值