Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push_back an array into a matrix c++

I need to insert an array of 10 elements in a matrix or vector of rows growing. What I would do is to enter the array as a row of the matrix of size n x 10. For the matrix push each array should then grow by 1 line. For each step of the iteration matrix will be:

[ 1 ] [ 10 ].. [ 2 ] [ 10 ] .. [ 3 ] [ 10 ]

I'm using std::array<int 10> for the construction of array.

like image 753
Ilario Piconese Avatar asked Jan 28 '26 22:01

Ilario Piconese


1 Answers

You can use the following container std::vector<std::array<int, 10>>

Here is a demonstrative program

#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;
    }        
}

The program output is

 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 
like image 97
Vlad from Moscow Avatar answered Jan 31 '26 13:01

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!