Home Item 1 - auto (中文)
Post
Cancel

Item 1 - auto (中文)

Auto

在C++11中,自動類型推斷(auto關鍵字)允許編譯器根據初始化表達式的類型推斷變量的類型,這使得程式碼更加簡潔且容易理解 ,反正就compiler 已經知道是什麼型別了,你就可以不用去寫,符合人性(惰性);其實現在的 IDE 已經很強大了,滑鼠移過去就可以看到型別了。一直寫型別反而有礙閱讀。

直接看 code

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

int main() {
    // 範例1:使用auto推斷整數類型
    auto x = 5; // x被推斷為int類型
    std::cout << "x: " << x << std::endl;

    // 範例2:使用auto推斷浮點數類型
    auto y = 3.14; // y被推斷為double類型
    std::cout << "y: " << y << std::endl;

    // 範例3:使用auto推斷複雜型別(如STL容器)
    std::vector<int> numbers = {1, 2, 3, 4, 5};
    for (auto it = numbers.begin(); it != numbers.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    return 0;
}

執行結果

Desktop View

使用時機:

  1. 當初始化表達式的類型很長或很複雜時,可以使用auto來使程式碼更加簡潔清晰。
  2. 當類型明顯可見且不易更改時,可以使用auto來提高程式碼的可讀性。
  3. 當使用範本編程或某些泛型代碼時,auto可以幫助減少重複類型名稱的錯誤並使程式碼更具靈活性。
  4. 當使用複雜的迭代器類型或STL容器時,auto可以減少錯誤並使程式碼更加簡潔。

☝ツ☝

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

👈 ツ 👍

30 items of modern C++ (from c++ 11 to c++20)(English)

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