我正在尝试堆叠/垂直连接 2D vector 。对于一维 vector ,我有这样的东西:
#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;
}
因此得到的二维 vector (矩阵):
1, 1, 1,
6, 6, 6,
是 vector a 和 b 的堆叠/垂直连接版本。现在,我有 a 和 b,它们是二维 vector 而不是一维 vector :
vector< vector<int> >a = {{1,2,3},
{2,2,2}};
vector< vector<int> >b = {{4,5,6},
{6,6,6}};
我如何将它们堆叠成一个大小为 4 x 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
那就是有很多方法可以完成任务。
关于c++ - 在 C++ 中堆叠/连接 2D vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31993677/