0

I have a vector of arbitrary size, and need to create a for loop from each entry from zero up to that number.

For example, if my list was {2,3,4}, I would need the following to run in my program.

for (unsigned int i = 0; i < 2; ++i}
  for (unsigned int j = 0; j < 3; ++j}
    for (unsigned int k = 0; k < 4; ++k}
      { do stuff }

My problem is that I don't know how many elements there are, and so I can't explicitly state the number of for loops that I need. I've thought about making a class that contains the list and overloading the + operator, iterating until the lists are equal, but I was hoping there was something that wasn't so messy. If not, I will have to be ok with that, I guess. Is there an cleaner way to do this than what I was thinking?

The reason that I need this is to iterate over all elements of an n-dimensional matrix, so my matrix could be 2 x 3 x 4 in the case I presented, but could have an arbitrary number of dimensions.

Thanks for any input.

  • `for (const auto& element : container) { ...` – Jesper Juhl Dec 20 '19 at 18:04
  • @JesperJuhl Wouldn't that just iterate over every element in container? – Jason Meziere Dec 20 '19 at 18:06
  • What do you mean by "My problem is that I don't know how many elements there are"? `std::vector` has `size` method, and with `std::list`, you can't access the elements by index anyway. This sounds like [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What is your exact problem? – Algirdas Preidžius Dec 20 '19 at 18:08
  • It's not clear what you are asking. When you say "arbitrary size" do you mean arbitrary dimensions or number of elements? A STL `vector` only supports one dimension and it's trivial to iterate its elements. Multiple loops would be needed for a multidimensional container. Can you clarify? – pcarter Dec 20 '19 at 18:09

1 Answers1

1

You could use a recursive loop function, like this:

#include <vector>

void looper(std::vector<int> vec, size_t index) {
    if (index >= vec.size()) return;
    for (int i = 0; i < vec[index]; ++i) {
        looper(vec, index + 1);
        if (index == vec.size() - 1) { // Innermost loop!
            // do something...
        }
    }
}

int main()
{
    std::vector<int> test{ 2, 3, 4 };
    looper(test, 0);
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83