[C++11] Instructions for using range-based for loop

1. Definition:

C++11 introduces range for-based for loop, which is a syntactic sugar that facilitates traversing containers or other iterable objects .

The syntax for a range-based forloop is as follows:

for (declaration : range) 
{
    
    
    // 循环体
}

Among them, declarationis a variable declaration used to store the element value in each iteration. It can be a custom variable name or an existing variable name. rangeIs the container or iterable object to be traversed, such as array, std::vector, std::listetc.

In each loop iteration, the variable declarationwill be automatically assigned the value of the element of the current iteration, and then the code in the loop body will be executed. The loop will iterate through rangeall the elements in until it is exhausted.

2. Use:

Example 1: Traverse std::vectorcontainers

#include <iostream>
#include <vector>

int main() 
{
    
    
    std::vector<int> numbers = {
    
    1, 2, 3, 4, 5};

    //使用基于范围的for循环遍历容器
    for (int num : numbers)    //可以使用auto自动类型推导
    {
    
    
        std::cout << num << " ";
    }
    
    std::cout << std::endl;
    return 0;
}
//result
1 2 3 4 5

When the compiler encounters a range-based forloop, it automatically converts it into a traditional iteration loop that iterates over the elements in the specified range.

Range-based forloops can be used on a variety of iterable objects, including arrays, container classes (such as std::vector, std::list, std::dequeetc.), strings, and custom iterable types.

During the loop, each iteration will get the next element from the specified range and assign it to the loop variable. This allows the loop variable to be used directly inside the loop body to operate on the current element without explicit access to the iterator or index.

Example 2: If you want to modify the elements in the container, you need to use references

#include <iostream>
#include <vector>

int main()
{
    
    
	std::vector<int> numbers = {
    
     1, 2, 3, 4, 5 };

	//使用基于范围的for循环遍历容器 - 使用引用修改元素
	for (auto& num : numbers)
	{
    
    
		num = num + 1;
	}

    //若无需修改容器中的元素,可以使用const限制
	for (const auto& num : numbers) 
	{
    
    
		std::cout << num << " ";
	}

	std::cout << std::endl;
	return 0;
}
//result
2 3 4 5 6

It can be seen that the range-based forloop makes traversing the container more concise and intuitive. There is no need to pay attention to the size and index of the container, only the element value in each iteration. This syntax improves code readability and simplicity in many scenarios.

Example 3: Using range-based forlooping to iterate over a custom type container

#include <iostream>
#include <vector>

class Point 
{
    
    
public:
    int x, y;

    Point(int x_, int y_) : x(x_), y(y_) {
    
    }
};

int main() 
{
    
    
    std::vector<Point> points = {
    
    {
    
    1, 2}, {
    
    3, 4}, {
    
    5, 6}};

    // 使用基于范围的for循环遍历容器
    for(const auto& point : points) 
    {
    
    
        std::cout << "x: " << point.x << ", y: " << point.y << std::endl;
    }

    return 0;
}
//result
x: 1, y: 2
x: 3, y: 4
x: 5, y: 6

In the loop of the above code, each pointobject is an element in the container, and its member variables can be accessed through point.xand . point.yRange-based forlooping makes traversing container elements concise and clear, and is more conducive to code maintenance.

3. Advantages:

The advantages of range-based forloops are as follows:

  1. No need to explicitly define iterators or index variables.
  2. Automatically handle container boundaries to avoid out-of-bounds access.
  3. Supports read-only access to elements, and cannot modify element values ​​in the container.
  4. The life cycle of a loop variable is limited to the current loop iteration and is no longer valid after the loop ends.
  5. The type of the loop variable can be a custom type, as long as the object supports the iterator access method.

If this article is helpful to you, I would like to receive a like from you!

Insert image description here

Guess you like

Origin blog.csdn.net/AAADiao/article/details/131082505