C++ has a range loop. A for loop that will run over all elements in the range you give it:
std::vector<int> v = {0, 1, 2, 3, 4, 5};
// ...
for (auto i : v)
std::cout << i << ' ';
std::cout << '\n';
You don't have to check for container size. The for loop will give you the next item in i, contained in v, at each loop execution. start to end.
At runtime, this loop is as performant as the traditional C loop. You don't need to index the item in the range yourself, and it's overflow safe.
But there are times where you use the old school index for something else. Maybe to print rows:
int myNumbers[] = {25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
int i;
for (i = 0; i < length; i++) {
printf("%d %d\n", i, myNumbers[i]);
}
The range for loop doesn't have an index. But if you need one, it's not hard to create one. The new construct has an initialiser clause you can use. The advantage of that initialiser is, that the variable you declare there, is not visible outside the loop. No scope leakage:
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (size_t inx = 0; auto i : v)
std::cout << inx++ << ": " << i << ' ';
std::cout << '\n';
Just a little code snippet that gives you all of the range for loop, and gives you that counter if you need it.
Thank you for reading.
-
Stuart_S
-
Cancel
-
Vote Up
0
Vote Down
-
-
Sign in to reply
-
More
-
Cancel
-
Jan Cumps
in reply to Stuart_S
-
Cancel
-
Vote Up
0
Vote Down
-
-
Sign in to reply
-
More
-
Cancel
-
Stuart_S
in reply to Jan Cumps
-
Cancel
-
Vote Up
0
Vote Down
-
-
Sign in to reply
-
More
-
Cancel
-
Jan Cumps
in reply to Stuart_S
-
Cancel
-
Vote Up
0
Vote Down
-
-
Sign in to reply
-
More
-
Cancel
Comment-
Jan Cumps
in reply to Stuart_S
-
Cancel
-
Vote Up
0
Vote Down
-
-
Sign in to reply
-
More
-
Cancel
Children