简体   繁体   中英

How to print out elements of 2d vector vertically in c++?

I have a simple vector of vectors of integers. The output of the below code will be

1 2 3 4 5 
6 7 8
9 10 11


I am trying to figure out how to get

1 6 9
2 7 10
3 8 11
4
5
int main() {
    using namespace std;
    vector<vector<int>> a  { {1,2,3,4,5}, {6,7,8}, {9,10,11} };
      for (int i = 0; i < a.size(); i++) {

        for (int j = 0; j < a[i].size(); j++ ) {
            
            cout << a[i][j] << " " ;
            
        }

        cout << endl;   
    }
    return 0;
};

Thank you!

In this line: cout << a[i][j] << " " ; , you just need to swap i and j .

#include <iostream>
#include <vector>
#include <cstddef> // for std::size_t
#include <algorithm>
int main() 
{
    std::vector<std::vector<int>> a  { {1,2,3}, {4,5,6}, {7,8,9} };
    std::size_t biggestSize{0};

    for(auto &i : a) biggestSize = std::max(biggestSize, i.size());

    for (std::size_t i {0}; i < biggestSize; ++i) // size() returns a std::size_t type
    {
        for (std::size_t j {0}; j < a.size(); ++j) //use postfix increment opreator instead of prefix
        {
             if(i >= a[j].size())
                 std::cout << "  ";
             else
                 std::cout << a[j][i] << ' ' ; // swap i and j
                 // because " " is just a character, repace it with ' '
        }
        std::cout << '\n'; //use newline character instead of std::endl  
    }
    return 0;
}

在第 13 行,只需将IJ交换:

cout << a[j][i] << " ";

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