1

Is there an elegant method of iterating through a multidimensional vector? Say, for instance, you have a 6D vector, though I think a 2D would suffice. Something like

vector< vector< int > myVector (6, vector<int> (5));

Is there a pretty way to iterate through this, starting from myVector[0][0], myVector[0][1], ...etc?? I was trying it on larger dimensions, and using the Auto keyword to generate an iterator, but it's no good. Here's what I was trying:

for(auto it = myVector.begin(); it < myVector.end(); ++it)
    std::cout << *it;

But it doesn't compile. Please forgive my rusty understanding of iterators in STL, it's been a long time...

Ali
  • 56,466
  • 29
  • 168
  • 265
Fulluphigh
  • 506
  • 1
  • 8
  • 21
  • See [this](http://stackoverflow.com/q/3623082/485561), perhaps the answer could be generalised to flatten an arbitrary (specified) number of dimensions. – Mankarse Nov 16 '12 at 06:14

1 Answers1

5

it is a vector<vector<int>>::iterator, and after applying the * you get back a vector<int>, which can't be printed out. You need to loop over the loop:

for(auto i1 = myVector.begin(); i1 != myVector.end(); ++i1) // loops over the "external" vector
    for(auto i2 = i1->begin(); i2 != i1->end(); ++i2) // loops over the "internal" vectors
        std::cout << *i2;

If you've got arbitrary dimensions, you can use the following:

template <typename T>
void printVar(const T& v)
{
    std::cout << v;
}

template <typename T>
void printVar(const std::vector<T>& v)
{
    for (auto i = v.cbegin(); i != v.cend(); ++i)
    {
        printVar(*i);
    }
}

Sample test.

Cornstalks
  • 37,137
  • 18
  • 79
  • 144
  • This is what I was afraid of, and what I'm doing now. I was hoping there was a way to do it without adding another loop for every additional dimension =P – Fulluphigh Nov 16 '12 at 06:17
  • Why do you think so? You iterate over vector why you would not iterate another vector? – Denis Ermolin Nov 16 '12 at 06:20
  • @JoshuaJefferies: I added code to allow you to print vectors of arbitrary dimensions. – Cornstalks Nov 16 '12 at 06:28
  • 1
    Also, a for-each loop would've been nice to use but my current compiler is a little behind the times and I wasn't able to test with for-each loops, so I went with `auto` style loops. – Cornstalks Nov 16 '12 at 06:29