【问题标题】:combine variables in a vector/matrix在向量/矩阵中组合变量
【发布时间】:2016-05-16 12:00:56
【问题描述】:

我是一名普通的 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 并分配变量?任何帮助表示赞赏。

【问题讨论】:

    标签: c++ c++11 visual-c++ matrix vector


    【解决方案1】:

    如果您希望能够在前面或后面插入,那么您应该使用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);
    

    【讨论】:

    • 但是a和b呢?
    • 我的答案现在应该有你想要的了。对于那个很抱歉!如果您认为可以,请采纳答案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    相关资源
    最近更新 更多