Chris said:
Hi,
is it possible to create a two dimensional array on the heap use a similar
syntax as with stack-vartiables :
On the stack :
int arr2[2][3];
arr2[0][2] = 7;
On the heap :
I tried : int *parr2 = new int [2][3];
but in vain --> compiler error
The only way i see is :
int *parr2 = new int [2 * 3];
but then
parr2[6] = 1; ==> not allowed to use 2-dim syntax :-((
Is there no other way ?
Don't do it! Use a class instead... Here is something to get you started:
template < typename T, typename U = std::deque< T > >
class Matrix {
public:
typedef typename U::size_type size_type;
typedef typename U::reference reference;
typedef typename U::const_reference const_reference;
typedef typename U::iterator iterator;
typedef typename U::const_iterator const_iterator;
Matrix(): h_limit( 0 ), v_limit( 0 ) { }
Matrix( size_type h, size_type v ):
buffer( h * v ), h_limit( h ), v_limit( v ) { }
reference operator()( size_type h, size_type v ) {
check_limits( h, v );
return buffer[h_limit * h + v];
}
const_reference operator()( size_type h, size_type v ) const {
check_limits( h, v );
return buffer[h_limit * h + v];
}
iterator begin() { return buffer.begin(); }
iterator end() { return buffer.end(); }
const_iterator begin() const { return buffer.begin(); }
const_iterator end() const { return buffer.end(); }
private:
void check_limits( size_type h, size_type v ) const {
if ( h >= h_limit || v >= v_limit )
throw std:
ut_of_range( "Matrix" );
}
U buffer;
size_type h_limit, v_limit;
};
The above was built with the help of the following:
int main() {
Matrix< double > m;
Matrix< char > m1( 2, 2 );
assert( m1( 0, 0 ) == 0 );
m1( 0, 0 ) = 1;
assert( m1( 0, 0 ) == 1 );
assert( m1( 0, 1 ) == 0 );
m1( 0, 1 ) = 2;
assert( m1( 0, 1 ) == 2 );
assert( m1( 1, 0 ) == 0 );
m1( 1, 0 ) = 3;
assert( m1( 1, 0 ) == 3 );
try {
m1( 2, 0 ) == 3;
assert( false && "out of range not caught h" );
}
catch ( out_of_range& err ) { }
catch ( exception& err ) {
cout << typeid( err ).name() << endl;
assert( false && "wrong error thrown h" );
}
try {
m1( 0, 2 ) == 3;
assert( false && "out of range not caught v" );
}
catch ( out_of_range& err ) { }
Matrix< char >::iterator begin = m1.begin();
assert( *begin++ == 1 );
assert( *begin++ == 2 );
assert( *begin++ == 3 );
assert( *begin++ == 0 );
assert( begin == m1.end() );
cout << "OK";
}