0

I have a 2D Vector matrix whose elements I want to shift into another 2D Vector result . The only thing is that the positions of the elements are changed in result by the logic shown in the code. The program that I have written gets executed but result displays all elements as 0 which is incorrect. How to fix this?

CODE

#include <bits/stdc++.h>
using namespace std;

int main() {
    
vector<vector<int>> matrix;
int n;

matrix = {{1,2},{3,4}};
n =  matrix.size();

//Loop to print `matrix` 
cout << "'matrix' 2D Vector" << endl; 

for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
        cout << matrix[i][j] << " ";
    }
    
    cout << "\n";
}

vector<vector<int>> result(n, vector<int> (n));

//Loop to shift elements from `matrix` to `result`     
for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
       result[j,n-i+1] = matrix[i][j];
    }
}

//Loop to print `result`
cout << "'result' 2D Vector" << endl;

for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
        cout << result[i][j] << " ";
    }
    
    cout << "\n";
}

    return 0;
}

OUTPUT

'matrix' 2D Vector
1 2
3 4

'result' 2D Vector
0 0
0 0

EXPECTED OUTPUT

'matrix' 2D Vector
1 2
3 4

'result' 2D Vector
3 1 
4 2
Ishan Dutta
  • 897
  • 4
  • 16
  • 36
  • 1
    https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h – Ulrich Eckhardt Nov 17 '20 at 07:19
  • [Why should I not `#include `?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Evg Nov 17 '20 at 07:33

1 Answers1

0

First only include <iostream> and <vector> header files instead of <bits/stdc++.h> and your code throws out_of_range exception because of the statement result[j][n-i+1] = matrix[i][j];, change it result[j,n-i-1] = matrix[i][j];

Harry
  • 2,177
  • 1
  • 19
  • 33