【发布时间】:2016-05-17 08:59:27
【问题描述】:
我需要在一个矩阵或行增长的向量中插入一个包含 10 个元素的数组。我要做的是将数组作为大小为n x 10 的矩阵的一行输入。对于矩阵 push,每个数组应该增加 1 行。对于迭代矩阵的每一步将是:
[1][10]..[2][10]..[3][10]
我使用std::array<int 10> 来构建数组。
【问题讨论】:
-
你有没有尝试过?
我需要在一个矩阵或行增长的向量中插入一个包含 10 个元素的数组。我要做的是将数组作为大小为n x 10 的矩阵的一行输入。对于矩阵 push,每个数组应该增加 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));
【讨论】: