Try the following
#include <iostream>
#include <vector>
#include <cstring>
template <class T>
std::ostream & print( T &c, std::ostream &os = std::cout )
{
for ( auto x : c ) os << x << ' ';
os << std::endl;
return os;
}
template <class T, size_t N>
std::ostream & print( T ( &a )[N], std::ostream &os = std::cout )
{
for ( auto x : a ) os << x << ' ';
os << std::endl;
return os;
}
template <class T>
std::ostream & print( T *a, size_t n, std::ostream &os = std::cout )
{
for ( auto p = a; p != a + n; ++p ) os << *p << ' ';
os << std::endl;
return os;
}
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
double b[] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
char s[] = "Hello zooombini";
std::vector<int> v1( a, a + sizeof( a ) / sizeof( *a ) );
std::vector<double> v2( b, b + sizeof( b ) / sizeof( *b ) );
print( a );
print( b );
print( v1 );
print( v2 );
print( s, std::strlen( s ) );
return 0;
}
The output is
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
H e l l o z o o o m b i n i
Or even you can add one more overloaded function
#include <iostream>
#include <vector>
#include <cstring>
template <class T>
std::ostream & print( T &c, std::ostream &os = std::cout )
{
for ( auto x : c ) os << x << ' ';
os << std::endl;
return os;
}
template <class T, size_t N>
std::ostream & print( T ( &a )[N], std::ostream &os = std::cout )
{
for ( auto x : a ) os << x << ' ';
os << std::endl;
return os;
}
template <class T>
std::ostream & print( T *a, size_t n, std::ostream &os = std::cout )
{
for ( auto p = a; p != a + n; ++p ) os << *p << ' ';
os << std::endl;
return os;
}
std::ostream & print( const char *s, std::ostream &os = std::cout )
{
return os << s << std::endl;
}
std::ostream & print( char *s, std::ostream &os = std::cout )
{
return os << s << std::endl;
}
int main()
{
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
double b[] = { 0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9 };
int *p = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
char s[] = "Hello zooombini";
std::vector<int> v1( a, a + sizeof( a ) / sizeof( *a ) );
std::vector<double> v2( b, b + sizeof( b ) / sizeof( *b ) );
print( a );
print( b );
print( p, 10 ) << std::endl;
print( v1 );
print( v2 );
print( s, std::strlen( s ) );
print( s );
delete []p;
return 0;
}
The output is
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9
H e l l o z o o o m b i n i
Hello zooombini