用法:
一是在變量聲明時根據初始化表達式自動推斷該變量的類型。適用於類型冗長復雜,模板類型等
二是在聲明函數時作為函數返回值的占位符
注意事項:
1.使用auto關鍵字的變量必須有初始值。類似引用
2.函數參數和模板參數不能被聲明為auto。
3.使用auto關鍵字聲明變量的類型,不能自動推導出頂層的CV-qualifiers和引用類型,除非顯示聲明
使用auto關鍵字進行類型推導時,如果初始化表達式是引用類型,編譯器會去除引用,除非顯示聲明
使用auto使用auto關鍵字進行類型推導時,編譯器會自動忽略頂層const,除非顯示聲明
使用場景
ex1:遍歷字符串
ex1:遍歷字符串
std::string str = “hello, world”;
for(auto ch : str) {
std::cout << ch << std::endl;
}
遍歷str,輸出每個字符,同時用上auto,簡直是如虎添翼。
ex2:遍歷數組
ex2:遍歷數組
int arr[] = {1, 2, 3, 4};
for(auto i : arr) {
std::cout<< i << std::endl;
}
ex3:遍歷stl 容器
std::vector<std::string> str_vec = {“i”, “like”, "google”};
for(auto& it : str_vec) {
it = “c++”;
}
ex4:遍歷stl map
std::map<int, std::string> hash_map = {{1, “c++”}, {2, “java”}, {3, “python”}};
for(auto it : hash_map) {
std::cout << it.first << “\t” << it.second << std::endl;
}
遍歷map返回的是pair變量,不是迭代器。