简体   繁体   English

如何在 C++ 中将 2D 向量的元素插入到另一个 2D 向量中?

[英]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 .我有一个 2D Vector matrix ,我想将其元素转换为另一个 2D Vector result The only thing is that the positions of the elements are changed in result by the logic shown in the code.唯一的事情是元素的位置在result被代码中显示的逻辑改变了。 The program that I have written gets executed but result displays all elements as 0 which is incorrect.我编写的程序被执行,但result显示所有元素为0 ,这是不正确的。 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];首先只包含<iostream><vector>头文件而不是<bits/stdc++.h>并且您的代码由于语句result[j][n-i+1] = matrix[i][j];抛出out_of_range异常result[j][n-i+1] = matrix[i][j]; , change it result[j,ni-1] = matrix[i][j]; , 改变它result[j,ni-1] = matrix[i][j];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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