将数组推回到矩阵c++中

push_back an array into a matrix c++

本文关键字:c++ 数组      更新时间:2023-10-16

我需要在增长的行的矩阵或向量中插入一个由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));