C++ doesn't support copying or comparing C-style arrays, but it does support such operations on very thinly-wrapped C-style arrays. Try boost::array
, which is the same as tr1::array
and std::array
in C++0x.
Or, roll your own:
#include <algorithm>
template< class T, size_t s >
struct array {
T arr[s]; // public data, no destructor, inheritance, virtuals, etc
// => type is aggregate
operator T const *() const { return arr; }
operator T *() { return arr; } // as close as we can get to array emulation
friend bool operator< ( array const &l, array const &r )
{ return std::lexicographical_compare( l, l+s, r, r+s ); }
};
array< char, 10 > names[] // aggregate initialization — this is standard C++
= { "JOHN", "PETER", "ARNOLD", "JACK" };
#include <iostream>
using namespace std;
int main() {
sort( names, names + sizeof names / sizeof *names );
for ( array<char,10> *s = names; s != names + sizeof names/sizeof*names; ++ s )
cerr << *s << endl;
}
If your compiler doesn't insanely add padding to the above structure, you can safely reinterpret_cast
a C-style array an an array
:
template< class T, size_t s >
array< T, s > &wrap_arr( T (&a)[s] ) {
return reinterpret_cast< array<T,s> & >( a );
// make sure the compiler isn't really wacky...
// I would call this optional:
BOOST_STATIC_ASSERT( sizeof( T[s] ) == sizeof( array<T,s> ) );
}
char names_c[][10] // or whatever C input from wherever
= { "JOHN", "PETER", "ARNOLD", "JACK" };
array<char, 10> *names = &wrap_arr( names_c[0] );