Is there a way to create for-loops of a form
for(int i = 0; i < 9; ++i) {
for(int j = 0; j < 9; ++i) {
//...
for(int k = 0; k < 9; ++k) { //N-th loop
without knowing N at the compile time. Ideally I'm trying to figure out a way to loop through separate elements of a vector of digits to create each possible number if a certain amount of digits is replaced with different digits.
Here is a nice little class for a multi-index that can be iterated via a range-based for-loop:
The basic idea is to use an array that holds a number of
dim
indices and then implementoperator++
to increase these indices appropriately.Use it as
Live On Coliru
I use this solution:
It can certainly optimized and adapted, but it works quite well and you don't need to pass parameters to a recursive function. With a separate function to increment the multi-index:
You could use a recursive function:
This will call recursively to loop_function N times, while each function will iterate calling loop_function
It may be a bit harder to program this way, but it should do what you want
I wrote some C++ 11 code implementing a N-nested for-loop for myself. Here is the main part of the code that can be used as a single .hpp import (I named it nestedLoop.hpp):
Here is an example with expected output:
You may use recursion instead with a base condition -
Now you don't need to provide the
baseCondition
value at compile time. You can provide it while calling thedoRecursion()
method.I'm going to take the OP at face value on the example code that was given, and assume what's being asked for is a solution that counts through an arbitrary base-10 number. (I'm basing this on the comment "Ideally I'm trying to figure out a way to loop through seperate elements of a vector of digits to create each possible number".
This solution has a loop that counts through a vector of digits in base 10, and passes each successive value into a helper function (doThingWithNumber). For testing purposes I had this helper simply print out the number.