在c++中堆叠/连接2D向量
Stacking/concatenate 2D vectors in C++
我正在尝试堆叠/垂直连接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
也就是说有很多方法来完成任务
相关文章:
- 2D数组来自文本输入,中间有空格
- 将值指定给向量(2D)的向量中的某个位置
- 如何使用用户输入在C++中正确填充2D数组
- 当套接字连接断开时检测C/C++Unix
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 四边形的 2D 旋转
- 打印第二列时的2d字符矢量打印空间
- 无法在windows上使用mingw将sqlite3与c连接
- 到连接组件算法的问题(递归)
- QTcpSocket在不阻塞GUI的情况下重新连接到服务器
- 无法在C++中建立与MySQL数据库的连接
- PC中的程序和PHONE中的本机描述应用程序之间的数据连接
- 在Qt Creator中,如何在连接到正在运行的进程后查看控制台输出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- qt如何连接QPushButton的2D数组并返回位置
- 如何连接 2D 数据数组
- 在c++中堆叠/连接2D向量
- 连接一个char 2D数组元素和c++中的int