[C++] Scope for detailed explanation and precautions

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 autobe simplified.
autoIt 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;
	}
}

Insert picture description here

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;
	}
}

Insert picture description hereIn 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:
Insert picture description here
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;
	}
}

Insert picture description here

Guess you like

Origin blog.csdn.net/zhaocx111222333/article/details/114970296