Transpose a matrix

Description: Transpose {{1,2,3},{4,5,6}} to {{1,4},{2,5},{3,6}}.

Hint:

  • The new matrix has cols rows and rows columns: t[j][i] = m[i][j].

Solution

#include <iostream>
#include <vector>

using Matrix = std::vector<std::vector<int>>;

Matrix transpose(const Matrix& m) {
    std::size_t rows = m.size(), cols = m[0].size();
    Matrix t(cols, std::vector<int>(rows));
    for (std::size_t i = 0; i < rows; i++)
        for (std::size_t j = 0; j < cols; j++)
            t[j][i] = m[i][j];
    return t;
}

int main() {
    for (const auto& row : transpose({{1, 2, 3}, {4, 5, 6}})) {
        for (int v : row) std::cout << v << ' ';
        std::cout << '\n';
    }
}
Output

1 4
2 5
3 6

How it works

  • A 2 x 3 matrix gives a 3 x 2 matrix, so the new vector has the sizes swapped.

Read C++ Vectors.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.