fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. std::vector<std::vector<int>>
  5. transpose (const std::vector<std::vector<int>>& input)
  6. {
  7. std::vector<std::vector<int>> res(input[0].size(), std::vector<int>(input.size()));
  8. for (std::size_t i = 0; i != input.size(); ++i) {
  9. for (std::size_t j = 0; j != input[i].size(); ++j) {
  10. res[j][i] = input[i][j];
  11. }
  12. }
  13. return res;
  14. }
  15.  
  16. void print(const std::vector<std::vector<int>>& m)
  17. {
  18. for (std::size_t i = 0; i != m.size(); ++i) {
  19. for (std::size_t j = 0; j != m[i].size(); ++j) {
  20. std::cout << m[i][j] << " ";
  21. }
  22. std::cout << std::endl;
  23. }
  24. }
  25.  
  26. int main ()
  27. {
  28. int width;
  29. int length;
  30.  
  31. std::cout << "enter the width followed by the length of the matrix: ";
  32. std::cin >> width >> length;
  33.  
  34. std::vector<std::vector<int>> input(width, std::vector<int> (length));
  35. std::cout << "enter elements \n";
  36. for (int j = 0; j < length; j++)
  37. for (int i = 0; i < width; i++) {
  38. std::cin >> input[i][j];
  39. }
  40.  
  41. std::cout << "your matrix is: \n";
  42. print(input);
  43. std::vector<std::vector<int>> output = transpose(input);
  44.  
  45. std::cout << "the transpose is: \n";
  46. print(output);
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 3480KB
stdin
2 3
1 2 3 4 5 6
stdout
enter the width followed by the length of the matrix: enter elements 
your matrix is: 
1 3 5 
2 4 6 
the transpose is: 
1 2 
3 4 
5 6