C++11 引入了一种新的 for 循环,让对一系列值(如数组包含的值)进行操作的代码更容易编写和 理解。
#include <iostream>
#include <string>
using namespace std;
int main()
{
// 整型
int someNums[] = {1,101,-1,40,2040};
for (auto elemente: someNums){
cout << elemente << " ";
}
cout << endl;
// 字符
char charArray[] = {'h','e','l','l','o'};
for (auto aChar: charArray){
cout << aChar << ' ';
}
cout << endl;
//字符串
string strArray = {"hello"};
for (auto strElement: strArray){
cout << strElement << ' ';
}
cout << endl;
}
值得注意的是
如果需要修改 数组之中的elemente
#include <iostream>
#include <string>
using namespace std;
int main()
{
// 整型 修改引用值
int someNums[] = {1,101,-1,40,2040};
for (auto elemente: someNums){
cout << elemente << " ";
}
cout << endl;
for (int &elemente: someNums){
elemente *=2;
}
for (auto elemente: someNums){
cout << elemente << " ";
}
cout << endl;
// 整型 不修改引用值
int someNums[] = {1,101,-1,40,2040};
for (auto elemente: someNums){
cout << elemente << " ";
}
cout << endl;
for (int elemente: someNums){
elemente *=2;
}
for (auto elemente: someNums){
cout << elemente << " ";
}
cout << endl;
}