简体   繁体   中英

Printing multidimensional arrays from a vector

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM