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
|
#include <vector>
#include <iostream>
using namespace std ;
// from a matrix, retrieve an nxn slice starting at row i, col j
// throws std::out_of_range on error
template< typename T >
vector< vector<T> > get_slice( const vector< vector<T> >& matrix, std::size_t n,
std::size_t i, std::size_t j )
{
const std::size_t N = matrix.size() ;
vector< vector<T> > slice(n) ;
for( std::size_t k = 0 ; k < n ; ++k )
for( std::size_t l = 0 ; l < n ; ++l )
slice[k].push_back( matrix.at(k+i).at(l+j) ) ;
return slice ;
}
// **** trivial test driver ******
template< typename T > void print( const vector< vector<T> >& matrix )
{
for( std::size_t i = 0 ; i < matrix.size() ; ++i )
{
for( std::size_t j = 0 ; j < matrix[i].size() ; ++j )
std::cout << matrix[i][j] << ' ' ;
std::cout << '\n' ;
}
std::cout << "--------------------\n" ;
}
int main()
{
enum { N = 5, M = 4 } ;
const int test_data[N][M] = { {1,2,3,4}, {5,6,7,8}, {9,0,1,2}, {3,4,5,6}, {7,8,9,0} } ;
vector< vector<int> > matrix(N) ;
for( int i = 0 ; i < N ; ++i ) matrix[i].assign( test_data[i], test_data[i] + M ) ;
print(matrix) ;
vector< vector<int> > block = get_slice( matrix, 2, 2, 1 ) ;
print(block) ;
block = get_slice( matrix, 3, 1, 1 ) ;
print(block) ;
}
|