What is the correct way of using C 11's range-based for?
C 11 introduced a new way to iterate over containers using range-based for, which is more concise and easier to read than traditional for loops. However, there are some rules to follow to use it correctly.
When using range-based for, you specify the type of the variable you want to iterate over, followed by a colon (:), and then the container you want to iterate through. For example:
for (int i : {1, 2, 3}) { // Do something with i } // Iterate over a vector of strings for (string s : my_vector) { // Do something with s }
The variable you specify in the for statement is automatically assigned the value of each element in the container as you iterate through it. This makes it very convenient to iterate over collections of data.
Which syntax should be used? for (auto elem : container), for (auto& elem : container), or for (const auto& elem : container)?
The syntax you should use depends on whether you want to modify the elements in the collection or not. If you want to modify the elements, you should use for (auto& elem : container). If you don't want to modify the elements, you can use either for (auto elem : container) or for (const auto& elem : container).
Using auto in the for statement means that the compiler will automatically deduce the type of the variable. This is convenient, but it can sometimes lead to errors if the compiler cannot correctly deduce the type. If you are not sure what type the variable should be, it is safer to specify it explicitly.
Using const in the for statement means that the variable cannot be modified within the loop. This is useful if you want to ensure that the elements in the collection are not accidentally changed.
Example:
// Modify the elements in a vector vector<int> my_vector = {1, 2, 3, 4, 5}; for (auto& elem : my_vector) { elem *= 2; } // Do something with the modified vector for (auto elem : my_vector) { cout << elem << endl; } // Iterate over a vector of const strings const vector<string> my_const_vector = {"Hello", "World", "!"}; for (const auto& elem : my_const_vector) { // Do something with elem cout << elem << endl; }
In the first example, we modify the elements in the vector by multiplying them by 2. In the second example, we iterate over a const vector of strings and print each element. Note that we cannot modify the elements in a const vector.
Conclusion:
Range-based for is a powerful tool that can make your code more concise and easier to read. By following the rules outlined above, you can use range-based for correctly to iterate over collections of data.
The above is the detailed content of How to Choose the Correct Syntax for C 11's Range-Based For Loop?. For more information, please follow other related articles on the PHP Chinese website!