2

In Python, code like this:

for i in range(1, 10):
  for j in range(1, 10):
    # Do something here

Can be replaced by code like this:

from itertools import product
  for i, j in product(range(1, 10), repeat=2):
    # Do something here

Is there some equivalent in C++?

Cisplatin
  • 2,860
  • 3
  • 36
  • 56
  • can try do while() or while() for nested loops – seccpur Oct 10 '16 at 01:24
  • 3
    Well, `itertools.product` is not really an alternative to nested for loops, it's an alternative to that particular pattern of nested for loops. Anyhow, it can be done by defining some special iterators, but AFAIK there's nothing ready made for that in the standard library. – Matteo Italia Oct 10 '16 at 01:24
  • 4
    There is no direct language feature to do this specifically, but it's possible to write C++ scaffolding that achieves it. The problem is that it will be less efficient than nested loops, harder for your compiler to optimize, and very irritating for other C++ programmers to read. – paddy Oct 10 '16 at 01:35
  • 2
    @paddy: well, exactly as the Python equivalent, I guess. =) – Matteo Italia Oct 10 '16 at 01:46
  • Eric Lippert's range-v3 or the corresponding TS sounds like what you are looking for. – NathanOliver Oct 10 '16 at 02:39

2 Answers2

0

I can think of at least 2 ways

A) Traditional multi-variable for loop (for the lack of better name)

for(int i =0, int j=0 ; i < 10 && j < 10;i++, j++) {
}

B) Using boost::zip_iterator as mentioned in this SO post

Community
  • 1
  • 1
JamesWebbTelescopeAlien
  • 3,547
  • 2
  • 30
  • 51
  • 3
    Your example A is not the same - it'll execute 10 times, not 100 - and `I == j` in each iteration. – davidbak Oct 10 '16 at 01:59
0

for loops in C are exceedingly simple and can be adapted to a variety of needs, the syntax for (init; condition; increment) accepts function calls in all of the 3 fields, allowing you to emulate any iteration pattern just by placing code in there calling the functions that generate the information you need on each loop.

Because of that possibility, it is unusual to use "ranges" like in Python. In C it makes more sense to calculate each index as you loop.

Havenard
  • 27,022
  • 5
  • 36
  • 62