Skip to content
Exercise · Containers and Iterators · lesson 11 of 11

Exercise: transpose a matrix

A matrix is stored by rows: m[i] is row i, and m[i][j] is the number in row i and column j. Write a function std::vector<std::vector<int>> transpose(const std::vector<std::vector<int>>& m) that returns the transposed matrix. In it, the number m[i][j] sits in row j and column i.

  • transpose({{1, 2, 3}}) → {{1}, {2}, {3}}
  • transpose({{1, 2}, {3, 4}}) → {{1, 3}, {2, 4}}
  • transpose({}) → {}

Constraints: the matrix is rectangular, with all rows of the same length and none of them empty. An empty matrix has no rows, and its result is empty too.

transpose.cpp — cpp
cpp · 6 lines
Ctrl+Enter run · Esc leave editor