`a

`auto` 在 C++

1 個練習

關於 `auto`

C++ 中的 auto 關鍵字

在 C++ 中,auto 關鍵字是 C++11 引入的強大功能,用來宣告型別會被推導出來的變數。 編譯器會根據初始值推導出變數的型別,讓程式碼更好閱讀、也更好維護。

使用範例

看看下面這個例子,auto 被用來宣告變數:

auto dragon_population{3};          // dragon_population is deduced as an integer
auto westeros{7.7777};              // westeros is deduced as a double
auto wedding_location{"The Twins"}; // wedding_location is deduced as a const char*, not std::string

在每個例子裡,變數的型別都是從初始化時所用的值推導出來的。

型別推導

auto 關鍵字省去了明確寫出型別的冗長,讓程式碼更精簡、也更好讀。

const std::vector<std::string> pigeon_pie{"flour", "butter", "pigeon", "salt"};
auto purple_wedding_pie{pigeon_pie};
purple_wedding_pie.emplace_back("the strangler");

在這段程式碼中,auto 把 purple_wedding_pie 的型別推導為 std::vector<std::string>,省下了再明確寫一次型別的麻煩。

相容性

auto 關鍵字可以和 C++ 的各種語法結構搭配使用,是現代 C++ 程式設計中靈活好用的一項工具。

auto& element{array[0]};           // reference to an element
const auto object{otherObject};    // const type version of otherObject's type
auto* ptr{&x};                     // pointer to x with the same type as x, but as a pointer.

在之後的單元裡,我們會經常看到 auto 關鍵字搭配 Lambda 表達式、範圍式 for 迴圈和迭代器。

使用情境

  • 泛型程式設計:在型別可能很複雜或跟樣板有關的泛型程式設計情境中,auto 特別好用。
  • 複雜的資料型態:面對複雜的資料型態或冗長的型別名稱時,auto 可以減少雜亂,提升程式碼的可維護性。
  • 以迭代器為基礎的演算法:它簡化了演算法中迭代器的使用,讓程式碼更好讀。
透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 `auto`

練習已鎖定

再解鎖 1 個練習,就能練習 `auto`