C++11 Practical Technology (4) How to write a for loop

Common usage

The method of traversing stl containers in C++ is usually:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
    1, 2, 3};
	for (auto it = arr.begin(); it != arr.end(); ++it)
	{
    
    
		std::cout << *it << std::endl;
	}
	return 0;
}

The above code needs to pay attention to the iterator, and also needs to display the begin and end of the container. Not convenient for writing. C++11 supports range-based for loops. as follows

C++11 range-based for loop

A C++11 range-based for loop looks like this:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
    1, 2, 3};
	for (auto n : arr)
	{
    
    
		std::cout << n << std::endl;
	}
	return 0;
}

You can also use references to modify the value of a container:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
    1, 2, 3};
	for (auto& n : arr)
	{
    
    
		n++;
	}
	//n的值为2,3,4
	return 0;
}

Map containers also support:

#include <iostream>
#include <map>
#include <string>

int main() {
    
    
	std::map<std::string, int> mp = {
    
     {
    
    "1",1}, {
    
    "2", 2}, {
    
    "3", 3} };
	for (auto& n : mp)
	{
    
    
		std::cout << n.first << " -> " << n.second << std::endl;
	}
	return 0;
}

Notice

However, range-based for loops do not support modifying the container during the loop:
for example:

#include <iostream>
#include <vector>

int main() {
    
    
	std::vector<int> arr = {
    
     1, 2, 3 };
	for (auto n : arr)
	{
    
    
		std::cout << n << std::endl;
		arr.push_back(4);//修改arr
	}
	return 0;
}

Running results:
Insert image description here
The main reason is that although the for loop above does not explicitly see the iterator, it is actually equivalent to using the iterator to traverse the values ​​of the container. When we modify the container object during the loop, the iterator will be modified, resulting in subsequent traversal. The values ​​are confused.

Guess you like

Origin blog.csdn.net/weixin_44477424/article/details/132307271