目录
auto
ex1:遍历字符串
std::string str = “hello, world”;
for(auto ch : str) {
std::cout << ch << std::endl;
}
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) {
cout << it << endl;
}
ex4:遍历stl map (遍历map返回的是pair变量,不是迭代器。)
map<int, string> hash_map = { {1, "c++"}, {2, "java"}, {3, "python"} };
for (auto it : hash_map) {
std::cout << it.first << "\t" << it.second << std::endl;
}