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
|
#include <iostream>
using namespace std;
// This function takes things the C way
void print_array( double* xs, int cols, int rows = 1 )
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
cout << xs[ (r * cols) + c ] << " ";
}
cout << "\n";
}
}
// These overloads do things the C++ way
// (but we simply pass along to the C way)
template <int C>
inline
void print_array( double (&xs)[ C ] )
{
print_array( (double*)xs, C );
}
template <int C, int R>
inline
void print_array( double (&xs)[ R ][ C ] )
{
print_array( (double*)xs, C, R );
}
int main()
{
double d1 [ 5 ] = { 1, 2, 3, 4, 5 };
double d2[ 2 ][ 5 ] = {{ 9, 8, 7, 6, 5 },
{ 4, 3, 2, 1, 0 }};
// The C way
cout << "d1\n"; print_array( (double*)d1, 5 );
cout << "d2\n"; print_array( (double*)d2, 5, 2 );
cout << "\n";
// The C++ way
cout << "d1\n"; print_array( d1 );
cout << "d2\n"; print_array( d2 );
return 0;
}
|