fork(1) download
  1. #include <type_traits>
  2. #include <vector>
  3. #include <iostream>
  4.  
  5. namespace
  6. {
  7. template <typename Container>
  8. struct value_type_i
  9. {
  10. typedef typename std::decay<
  11. decltype(*std::begin(std::declval<
  12. Container const &
  13. >()))
  14. >::type type;
  15. };
  16.  
  17. template <typename Container>
  18. using value_type = typename value_type_i<Container>::type;
  19. }
  20.  
  21. template <typename MatrixType>
  22. MatrixType transpose(MatrixType const & matrix)
  23. {
  24. auto const nrows = matrix.size();
  25. auto const ncols = nrows > 0 ? matrix[0].size() : 0;
  26.  
  27. MatrixType transposed(ncols, value_type<MatrixType>(nrows));
  28. for(auto k = 0; k < nrows; ++k)
  29. for(auto j = 0; j < ncols; ++j)
  30. transposed[j][k] = matrix[k][j];
  31.  
  32. return transposed;
  33. }
  34.  
  35. template <typename T>
  36. void print(T const & t)
  37. {
  38. for(auto const & row : t)
  39. {
  40. for(auto const & col : row)
  41. std::cout << col << ' ';
  42. std::cout << '\n';
  43. }
  44. std::cout << '\n';
  45. }
  46.  
  47. int main()
  48. {
  49. std::vector<std::vector<int>> A(7, std::vector<int>(9));
  50. int val = 11;
  51. for(auto & row : A)
  52. for(auto & col : row)
  53. col = val++;
  54. print(A);
  55. print(transpose(A));
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
11 12 13 14 15 16 17 18 19 
20 21 22 23 24 25 26 27 28 
29 30 31 32 33 34 35 36 37 
38 39 40 41 42 43 44 45 46 
47 48 49 50 51 52 53 54 55 
56 57 58 59 60 61 62 63 64 
65 66 67 68 69 70 71 72 73 

11 20 29 38 47 56 65 
12 21 30 39 48 57 66 
13 22 31 40 49 58 67 
14 23 32 41 50 59 68 
15 24 33 42 51 60 69 
16 25 34 43 52 61 70 
17 26 35 44 53 62 71 
18 27 36 45 54 63 72 
19 28 37 46 55 64 73