在C++代码中经常遇到for(auto&a:vec)用法,下面用一个demo查看他们的用处。
#include<iostream>
#include<vector>
int main()
{
std::vector<std::string>toppings{"abcd","ab"};
toppings.push_back("efg");
for (auto& topping : toppings)
{
std::cout << " " + topping + "\n";
}
std::string str("abc");
for (auto& s : str)
{
std::cout <<s<<std::endl;
std::cout <<&s<<std::endl;
}
return 0;
}
输出结果为:
当for循环中迭代vector时,输出的是vector中每个元素(vector的string),当for循环中迭代string时,输出的是string中每个元素(string中的char字符),可以发现迭代器s在累加。