auto: yêu cầu compiler tự suy kiểu (type deduction) từ biểu thức khởi tạo.
cpp
auto x = 42; // int
auto y = 3.14; // double
// Đặc biệt hữu ích với kiểu dài:
std::map<std::string, std::vector<int>> m;
auto it = m.begin(); // thay vì: std::map<std::string, std::vector<int>>::iteratorRange-based for (C++11):
cpp
std::vector<int> v = {1, 2, 3};
for (int x : v) // copy
for (int& x : v) // reference — có thể sửa
for (const int& x : v) // const ref — đọc không copy
for (auto& x : v) // auto + ref — tốt nhất cho mọi kiểuLưu ý: auto& x giữ reference; auto x luôn copy kể cả với reference source.
auto: asks the compiler to deduce the type from the initialisation expression.
cpp
auto x = 42; // int
auto y = 3.14; // double
// Especially useful for verbose types:
std::map<std::string, std::vector<int>> m;
auto it = m.begin(); // instead of: std::map<std::string, std::vector<int>>::iteratorRange-based for (C++11):
cpp
std::vector<int> v = {1, 2, 3};
for (int x : v) // copy
for (int& x : v) // reference — can modify
for (const int& x : v) // const ref — read-only, no copy
for (auto& x : v) // auto + ref — best default for any typeNote: auto& preserves reference; plain auto always copies even from a reference source.