📜  c++ foreach - C++ (1)

📅  最后修改于: 2023-12-03 15:13:54.215000             🧑  作者: Mango

C++ foreach

In C++, the foreach loop is used to iterate over every element in an array, vector, or other container. This provides a convenient way to process each element without having to manually manage the loop counter.

Syntax:
for (const auto& element : container) {
    // ...
}

In this syntax, container is the data structure being iterated over (e.g. array, vector, etc.), and element is a const reference to the current element being processed. The loop body can then manipulate element as needed.

The auto keyword allows the compiler to automatically determine the type of the element variable based on the type of the container.

Example:
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v {1, 2, 3, 4, 5};
    for (const auto& elem : v) {
        std::cout << elem << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output:

1 2 3 4 5

In this example, a vector<int> is created with 5 elements. The foreach loop then iterates over each element in the vector and prints it to the console.

Conclusion:

Using foreach loops in C++ can make code more concise and readable, especially when dealing with containers. However, it is important to note that foreach loops can have performance implications depending on the size and complexity of the container being iterated over. It is always a good idea to profile your code and determine if foreach loops are the best choice for your particular use case.