Question

I have multiple multidimensional arrays stored in a vector, but I seem to effectively print them. I always get either the first line of the array or no output depending on what I try.

This is how I attempt to print out the multidim arrays:

     int vecSize = myVec.size();

     for (int x = 0; x < vecSize; x++){
       for (int y=0; y <vecSize; y++){
           cout<<myVec[x][y]<<endl;
        }
      }

This is how I place the arrays in the vector:

    myVec.push_back(myMultiDArray);

Any suggestions on how to improve this?

Was it helpful?

Solution

You have an error in the loop condition: the inner loop iterates up to the same bound as the outer one. This is almost certainly wrong, it should iterate to the size of the current line vector. Like this:

for (size_t x = 0, vecSize = myVec.size(); x < vecSize; x++) {
    std::vector<int>& curVec = myVec[x];

    for (size_t y = 0, curSize = curVec.size(); y < curSize; y++) {
        cout << curVec[y] << " ";
    }

    cout << "\n";
}

This code will work flawlessly for any shape of the 2D array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top