如何在 C++ 中垂直打印二维向量的元素?

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

我有一个简单的整数向量向量。 以下代码的输出将是

1 2 3 4 5 
6 7 8
9 10 11


我正在想办法得到

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;
};

谢谢!

在第 13 行中,将 IJ 交换:

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

在这一行中:cout << a[i][j] << " " ;,您只需交换 ij

#include <iostream>
#include <vector>
#include <cstddef> // for std::size_t
#include <algorithm>
// using namespace std; is bad, so don't use it.
int main() 
{
    std::vector<std::vector<int>> a  {{1,2,3,4,5}, {6,7,8}, {9,10,11}};
    std::size_t biggestSize{0};

    for(const auto &i : a) 
    {
        if(biggestSize < i.size())
        {
            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
             }
        }
        std::cout << '\n'; //use newline character instead of std::endl  
    }
    return 0;
}