2

In modern C++, the idiom for iterating a sequential collection like string or vector when you only need the value of each element is short and elegant:

for (auto x: xs)

When you also need the index, it's a little less elegant:

for (size_t i = 0; i != xs.size() ++i)

... unless there's some recent development I haven't yet caught up with. Does C++11 have a preferred way of doing the latter, or is the above still as good as it gets?

rwallace
  • 31,405
  • 40
  • 123
  • 242
  • What about use zip_iterator to zip your iterator with a counting_iterator? You can write a generic container wrapper class that works on iterators of this type. – sbabbi Jan 19 '13 at 06:20
  • See this question: http://stackoverflow.com/questions/7185437/is-there-a-range-class-in-c11-for-use-with-range-based-for-loops – Omnifarious Jan 19 '13 at 06:38

3 Answers3

2

Range-Based for loops will be very popular in the modern code, Range-Based for Loops is valid for any type supporting the notion of a range. Given object obj of type T, begin(obj) and end(obj) are valid. Includes:

  • All C++11 library containers.
  • Arrays and valarrays.
  • Initializer lists.
  • Regular expression matches.
  • Any UDT(user defined type) T where begin(T) and end(T) yield suitable iterators.
billz
  • 44,644
  • 9
  • 83
  • 100
1

The preferred and idiomatic way is the simple for loop.

Alternative methods include using an integer range:

template<typename C>
auto container_index(C const& container) -> decltype(boost::irange(0, container.size())) {
  return boost::irange(0, container.size());
}

for(auto x : container_index(xs))

Or an iterating function:

template<typename F>
void index_iterate(std::size_t size, F func) {
  for(std::size_t i = 0; i != size; ++i) {
    func(i);
  }
}

index_iterate(container.size(), [&](std::size_t i){ /* ... */ });

Just go with the simple loop whenever possible though. It's superior in my opinion.

Pubby
  • 51,882
  • 13
  • 139
  • 180
0

You can combine two methods:

int i = 0;
for ( auto x : v ) {
    // do smth with x or v[i] or i
    i++;
}
borisbn
  • 4,988
  • 25
  • 42