11.9k views
1 vote
The range-based for loop, in C++ 11, is designed to work with a built-in variable known as the ________.

A) counter variable
B) i variable
C) iterator
D) range variable
E) None of these

User Rico Yao
by
9.3k points

1 Answer

3 votes

Final answer:

The range-based for loop in C++ 11 is designed to work with the 'iterator'. This for loop simplifies iterating over elements in a container like std::vector or std::list.

Step-by-step explanation:

The range-based for loop in C++11 is designed to work with a built-in variable known as the iterator. This type of for loop automatically iterates over all elements of a collection, such as an array or a container that supports the begin and end methods, like std::vector or std::list. This makes iterating over elements of a container more concise and less prone to errors because you do not need to manually manage the iteration as you would have to with a traditional for loop using a counter variable.

Here is an example of how a range-based for loop is typically used:

std::vector<int> myVector = {1, 2, 3, 4, 5};
for (int x : myVector) {
// Process each element x
}

In this example, x is a copy of each element in myVector as the loop iterates over it. Instead of using an index to access elements, the range-based for loop gives a direct reference to each element in the sequence.

User PinkFloydRocks
by
7.9k points