how to print the transpose of a 2d vector with different number of columns?

Let’s try to concentrate on the task at hand. You want to print a matrix. If an entry of the matrix does not exist, you want to print a space character.

Printing the matrix is usually done with two nested loops:

for(int row = 0; row < rows; ++row)
    for(int col = 0; col < cols; ++col)
        ...

Checking if an element exists can be done using the vector length:

if(row < tbl[col].size())
    // element exists

Putting all together:

#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<int>> tbl =
    {
       {4},
       {4, 2},
       {4, 2, 7},
       {4, 2, 7},
       {4, 2, 7, 5},
    };


    size_t cols = tbl.size();

    // find the number of rows
    size_t rows = 0;
    for (auto& col : tbl)
        if (col.size() > rows)
            rows = col.size();

    for (size_t row = 0; row < rows; ++row)
    {
        for (size_t col = 0; col < cols; ++col)
        {
            // check if the element exists
            if (row < tbl[col].size())
                // it exists, print it
                std::cout << tbl[col][row];
            else
                // it does not exist, print a space
                std::cout << " ";

            // separating space
            std::cout << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top