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
|
struct boolarray
{
unsigned size;
bool* data;
// Useful ctor and dtor
boolarray( unsigned n ): size( n ), data( n ? (new bool[ n ]) : NULL ) { }
~boolarray() { if (data) delete [] data; }
// Helper to construct from static data, see main() function
boolarray( const bool* a, unsigned n )
{
size = n;
data = new bool[ size ];
for (unsigned x = 0; x < size; x++)
data[ x ] = a[ x ];
}
// Alas, you need this copy ctor and assignment operator for
// things to work properly with your add() function.
boolarray( const boolarray& a )
{
data = NULL;
copy( a );
}
boolarray& operator = ( const boolarray& a )
{
copy( a );
return *this;
}
void copy( const boolarray& a )
{
if (data) delete [] data;
size = a.size;
data = new bool[ size ];
for (unsigned n = 0; n < size; n++)
data[ n ] = a.data[ n ];
}
// accessors
const bool& operator [] ( unsigned n ) const { return data[ n ]; }
bool& operator [] ( unsigned n ) { return data[ n ]; }
};
boolarray add( boolarray a, boolarray b )
{
boolarray c( ((a.size > b.size) ? a.size : b.size) + 1 );
for (unsigned n = 0; n < c.size; n++)
{
if (a[n] || b[n])
...
}
return c;
}
int main()
{
bool _a[] = {1, 1, 0, 1};
bool _b[] = {1, 0, 1, 1, 0};
boolarray a( _a, sizeof(_a)/sizeof(bool) );
boolarray b( _b, sizeof(_b)/sizeof(bool) );
boolarray c = add( a, b );
for (unsigned n = 0; n < c.size; n++)
cout << c[n] << " ";
return 0;
}
|