//随机定义的数组
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < 10; i++) {
cout << array[i] << " "; //输出:1 2 3 4 5 6 7 8 9 10
}
//随机定义的数组
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (auto a : array) { //这里的auto可以改成int,auto自动匹配类型
cout << a << " "; //输出:1 2 3 4 5 6 7 8 9 10
}
用法为:for(变量类型 变量名称 : 容器/数组等)
#include<iostream>
#include<vector>
int main()
{
std::vector<int> array;
array.push_back(1);
array.push_back(2);
array.push_back(3);
for (auto n : array) //只读的方式输出!若需要修改里边的值,可以使用 for(auto& n:array)
{
std::cout << n << std::endl;
}
return 0;
}
//输出:
//1
//2
//3