Here goes:
void foo()
{
int a[5];
int len = 0;
// push back
a[len++] = x;
//...
}
After some time time I get annoyed with writing too much code per single conceptual operation and scribble something like this:
template< typename T, int N >
struct array
{
T a[N];
int len;
array() : len(0) {}
void push_back( T v ) { a[len++] = v; }
T& operator[] ( int i ) { return a[i]; }
};
This is great for little things that don't require any construction. Like primitive types. For proper classes that have constructor, copy constructors etc, we'd need at least these:
1. Take const reference parameters.
2. Not construct N instances on construction of our array class.
3. Construct or destruct T when the user expects it - on addition or removal
Like this:
template< typename T, int N >
struct array
{
char a[ N * sizeof(T) ];
int len;
array() : len(0) {}
T& at( int i ) { return *(T*)( a + i * sizeof(T) ); }
void push_back( const T& v ) { at(len++).T(v); } // call copy constructor
T& operator[] ( int i ) { return at(i); }
};
void erase_unordered( int i ) {
at(i) = at(--len);
at(len).~T();
}
This would probably be nicer with C++11 move semantics.
What I really think is that STL should provide this. They did add std::array in C++11 but it does not cover variable length like here. Maybe it warrants a separate class? not sure.
So, guys, do you hear me up there?
No comments:
Post a Comment