The scope for was introduced in C++11, and he has several points worth paying attention to.
Generally write like this:
for(auto e:obiect)
cout<<e;
e is the variable used for iteration.
=Object is an object. Range for is actually implemented by iterators. Only custom types that support iterator access can support range for loops.(For example: initialization list, string, array, etc.)
General use:
void test(){
int arr[5] = {
1, 2, 3, 4, 5 };
char arr1[6] = "hello";
for (int e : arr){
cout << e << endl;
}
cout << "--------"<<endl;
for (char e : arr1){
cout << e << endl;
}
}
It can auto
be simplified.
auto
It is based on the following value to automatically infer the previous data type:
void test(){
int arr[5] = {
1, 2, 3, 4, 5 };
char arr1[6] = "hello";
for (auto e : arr){
cout << e << endl;
}
cout << "--------"<<endl;
for (auto e1 : arr1){
cout << e1 << endl;
}
}
Modify the data through the for loop:
void test(){
int arr[5] = {
1, 2, 3, 4, 5 };
for (auto e : arr){
e = e + 1;
cout << e << endl;
}
}
In this code, we see that the printing of e is in line with expectations, but we debug arr and find that it is only a copy, and the actual arr has not changed:
to modify the array through the range for, you need to pass a reference:
void test(){
int arr[5] = {
1, 2, 3, 4, 5 };
for (auto &e : arr){
e = e + 1;
cout << e << endl;
}
}