简体   繁体   中英

How to insert element of a 2D Vector into another 2D vector in C++?

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

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,ni-1] = matrix[i][j];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM