Home Item 2 - range-based for loop (中文)
Post
Cancel

Item 2 - range-based for loop (中文)

range-based for loop

C++11中引入了範圍for循環(range-based for loop),使得遍歷容器中的元素更加方便和直觀。

直接看 code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>

int main() {
    // 創建一個整數向量
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    // 使用範圍for循環遍歷容器中的元素
    for (auto x : numbers) {
        std::cout << x << " ";
    }
    std::cout << std::endl;

    return 0;
}

執行結果

Desktop View

使用時機:

  1. 當需要遍歷容器(如向量、列表、映射等)中的所有元素時,範圍for循環提供了一種簡潔且易於理解的語法。
  2. 當不需要索引值或迭代器,只需訪問容器中的元素時,範圍for循環更加方便。

功能不變,但好讀很多! 就是這麼簡單!

☝ツ☝

This post is licensed under CC BY 4.0 by the author.

👈 ツ 👍

Item 1 - auto (中文)

Item 1 - auto (English)