Logo

Programming-Idioms

History of Idiom 7 > diff from v78 to v79

Edit summary for version 79 by mrgroggle:
[Cpp] Static variable was unnecessary, vector also unnecessary (array-like doesn't have to be a vector type)

Version 78

2019-09-29, 17:10:14

Version 79

2019-10-07, 08:54:26

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Idiom #7 Iterate over list indexes and values

Print each index i with its value x from an array-like collection items

Extra Keywords
traverse traversal
Extra Keywords
traverse traversal
Imports
#include <iostream>
#include <vector>
Imports
#include <iostream>
Code
for(const auto & item : items) {
  static auto idx = 0;
  std::cout << "Item " << idx++ << " = " << item << std::endl;
}
Code
std::size_t i = 0;
for(const auto & x: items) {
  std::cout << "Item " << i++ << " = " << x << std::endl;
}
Comments bubble
Uses the C++11 features "range based for loop" and "auto". Index is initialized to zero only once for the entire program regardless of how many times this loop is run. Also not thread safe.
Comments bubble
Uses the C++11 features "range-based for loop" and "auto".
Doc URL
http://en.cppreference.com/w/cpp/language/range-for
Doc URL
http://en.cppreference.com/w/cpp/language/range-for