在c++中堆叠/连接2D向量

Stacking/concatenate 2D vectors in C++

本文关键字:连接 2D 向量 c++      更新时间:2023-10-16

我正在尝试堆叠/垂直连接2D向量。对于1D向量,我有这样的东西:

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    vector< vector<int> > res;//(2,vector<int>(3,0.0));
    vector<int>a = {1,1,1};
    vector<int>b = {6,6,6};
    res.push_back(a);
    res.push_back(b);
    for(int i = 0; i < res.size(); i++)
    {
        for(int j = 0; j < res[0].size(); j++)
        {
            cout << res[i][j] << ",";
        }
        cout << endl;
    }
    return 0;
}

因此得到的2D向量(矩阵):

1, 1, 1,
6, 6, 6,

是向量a和b的堆叠/垂直连接版本。现在,我有a和b是2D向量而不是1D向量:

 vector< vector<int> >a = {{1,2,3},
                            {2,2,2}};
  vector< vector<int> >b = {{4,5,6},
                            {6,6,6}};

我该如何将它们堆叠成一个大小为4 × 3的矩阵呢?

1, 2, 3,
2, 2, 2,
4, 5, 6,
6, 6, 6,

因为,简单的push_back()是不行的。

你的意思是:

#include <iostream>
#include <vector>
int main()
{
    std::vector<std::vector<int>> a = { { 1, 2, 3 }, { 2, 2, 2 } };
    std::vector<std::vector<int>> b = { { 4, 5, 6 }, { 6, 6, 6 } };
    std::vector<std::vector<int>> res;
    res = a;
    res.insert( res.end(), b.begin(), b.end() );
    for ( const auto &row : res )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        
}    

程序输出为

1 2 3 
2 2 2 
4 5 6 
6 6 6 

也可以使用push_back。例如

#include <iostream>
#include <vector>
#include <functional>
int main()
{
    std::vector<std::vector<int>> a = { { 1, 2, 3 }, { 2, 2, 2 } };
    std::vector<std::vector<int>> b = { { 4, 5, 6 }, { 6, 6, 6 } };
    std::vector<std::vector<int>> res;
    res.reserve( a.size() + b.size() );
    for ( auto &r : { std::cref( a ), std::cref( b ) } )
    {
        for ( const auto &row : r.get() ) res.push_back( row );
    }        
    for ( const auto &row : res )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        
}    

输出将与上面的相同

1 2 3 
2 2 2 
4 5 6 
6 6 6 

或者你可以这样写

#include <iostream>
#include <vector>
#include <functional>
int main()
{
    std::vector<std::vector<int>> a = { { 1, 2, 3 }, { 2, 2, 2 } };
    std::vector<std::vector<int>> b = { { 4, 5, 6 }, { 6, 6, 6 } };
    std::vector<std::vector<int>> res;
    res.reserve( a.size() + b.size() );
    for ( auto &r : { std::cref( a ), std::cref( b ) } )
    {
        res.insert( res.end(), r.get().begin(), r.get().end() );    
    }        
    for ( const auto &row : res )
    {
        for ( int x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }        
}    
1 2 3 
2 2 2 
4 5 6 
6 6 6 

也就是说有很多方法来完成任务