将数组推回到矩阵c++中
push_back an array into a matrix c++
我需要在增长的行的矩阵或向量中插入一个由10个元素组成的数组。我要做的是将数组输入为大小为n x 10
的矩阵的一行。对于矩阵推送,每个数组应该增长1行。迭代矩阵的每一步都是:
[1][10]。。[2][10]。。[3][10]
我使用std::array<int 10>
来构造阵列。
您可以使用以下容器std::vector<std::array<int, 10>>
这是一个演示程序
#include <iostream>
#include <iomanip>
#include <array>
#include <vector>
int main()
{
const size_t N = 10;
std::vector<std::array<int, N>> matrix;
matrix.push_back( { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 } } );
for ( const auto &row : matrix )
{
for ( int x : row ) std::cout << std::setw( 2 ) << x << ' ';
std::cout << std::endl;
}
std::cout << std::endl;
std::array<int, N> a = { { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 } };
matrix.push_back( a );
for ( const auto &row : matrix )
{
for ( int x : row ) std::cout << std::setw( 2 ) << x << ' ';
std::cout << std::endl;
}
}
程序输出为
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
如果我很好地理解您的问题,一个可能的解决方案是:
std::vector<std::vector<T>> my_matrix;
....
std::array<T,10> my_array;
...
std::vector<T> temp;
temp.reserve(10);
std::copy(std::begin(my_array),std::end(my_array),std::back_insertor(temp));
my_matrix.emplace_back(std::move(temp));
甚至更好:
std::vector<std::vector<T>> my_matrix;
....
std::array<T,10> my_array;
...
my_matrix.emplace_back(std::begin(my_array),std::end(my_array));
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '