1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
#include <iostream>
#include <iomanip>
#include <vector>
#include <cassert>
using namespace std;
using vec = vector<int>; // aliases to avoid long type expressions
using matrix = vector<vec>;
int fieldWidth = 10; // field width to output matrix elements
//=====================================================================
// Extract a submatrix of m rows and n columns, starting at i0, j0
//=====================================================================
matrix subMatrix( const matrix &M, int i0, int j0, int m, int n )
{
assert( i0 >= 0 && i0 + m - 1 < M.size() && j0 > 0 && j0 + n - 1 < M[0].size() ); // check validity
matrix result( m, vec( n ) );
for ( int i = 0; i < m; i++ )
{
for ( int j = 0; j < n; j++ ) result[i][j] = M[i0+i][j0+j];
}
return result;
}
//=====================================================================
// Overwrite a matrix with submatrix, starting at i0, j0
//=====================================================================
void addToMatrix( const matrix &S, matrix &M, int i0, int j0 )
{
int m = S.size(), n = S[0].size(); // get submatrix size
assert( i0 >= 0 && i0 + m - 1 < M.size() && j0 > 0 && j0 + n - 1 < M[0].size() ); // check validity
for ( int i = 0; i < m; i++ )
{
for ( int j = 0; j < n; j++ ) M[i0+i][j0+j] = S[i][j];
}
}
//======================================================================
// Overload << operator to output a matrix
//======================================================================
ostream &operator << ( ostream &out, const matrix &M )
{
for ( auto &row : M )
{
for ( auto e : row ) out << setw( fieldWidth ) << e << ' ';
out << '\n';
}
return out;
}
//======================================================================
// Driver program
//======================================================================
int main()
{
// Original matrix
matrix M = { { 0, 1, 2, 3, 4 }, { 10, 11, 12, 13, 14 }, { 20, 21, 22, 23, 24 }, { 30, 31, 32, 33, 34 },
{ 40, 41, 42, 43, 44 }, { 50, 51, 52, 53, 54 }, { 60, 61, 62, 63, 64 } };
int r = M.size(), c = M[0].size();
// Blank matrix of same size
matrix B = vector<vec>( r, vec( c, 0 ) );
// Submatrix size and location
int i0 = 4, j0 = 2, subr = 2, subc = 2;
// Grab submatrix from M
matrix S = subMatrix( M, i0, j0, subr, subc );
// And stick it in the same position in the blank matrix
addToMatrix( S, B, i0, j0 );
// Now let's see what we've got
cout << "Original matrix:\n" << M << '\n';
cout << "Submatrix:\n" << S << '\n';
cout << "Put into blank matrix (at same location): \n" << B << '\n';
}
|