在向量/矩阵中组合变量

combine variables in a vector/matrix

本文关键字:组合 变量 向量      更新时间:2023-10-16

我是MATLAB的普通用户,但对c++不熟悉。如果有人能帮助我解决问题,我将不胜感激。

我几乎没有变量和向量。

#include<iostream>
#include<vector>
int main(){
int a=1; int b=1;
vector<int> V1(100,0);
vector<int> V2(100,0);
return 0;
}

我想将所有变量(a,b,V1,V2)组合在一个 2x101 矩阵(比如 M)中,其中 M 的第一行和第二行是

M[0] = {a,V1};
M[1] = {V2,b};

如何定义 M 并分配变量?任何帮助,不胜感激。

如果您希望

能够在前面或后面插入,那么您应该使用std::deque。所以你可以做到以下几点

deque<deque<int>> M;
M.push_back(V1);
M.push_front(a);
M.push_back(V2);
M[1].push_back(b);

这将创建一个二维数组或矩阵,其中两个向量作为行。

或者您可以创建一个二维向量并手动填充元素

vector<vector<int>> M;
M.resize(2);
// Reserve space for efficiency reasons, this prevents reallocation
M[0].reserve(V1.size() + 1);
M[0].push_back(a);
for (auto integer : V1) {
    M[0].push_back(integer);
}
M[1].reserve(V2.size() + 1);
for (auto integer : V2) {
    M[1].push_back(integer);
}
M[1].push_back(b);