Home > other >  How to print out elements of 2d vector vertically in c ?
How to print out elements of 2d vector vertically in c ?

Time:10-24

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!

CodePudding user response:

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

CodePudding user response:

In line 13 just swap I with J:

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