I have been writing C++ for a little while (java/C for a long while), I am wondering if there is a trick I don’t know which can help me do the following.
vector<unsigned char> *fromArray(unsigned char data[], int length)
{
vector<unsigned char> *ret = new vector<unsigned char >();
while (length--)
{
ret->push_back(*data);
}
return ret;
}
And you can use it like so:
unsigned char tmp[] = {0, 1, 2, 3, 4, 5};
vector<unsigned char> *a = fromArray(tmp, sizeof(tmp));
// use `a' here
I find that pretty cumbersome – I’d like to write it all on one line
vector<unsigned char> *a = fromArray({0, 1, 2, 3, 4, 5});
// use `a' here
Is such a thing possible? I don’t have access to C++11 unfortunately (looks like its initializer_list is exactly what I want).
EDIT
Sorry I had some of the fundamentals wrong in here. I will now avoid extending std::vector. However I think the question is still valid, just that my example was a bad one.
** Potential workaround **
I could define a bunch of overloaded functions to take different numbers of arguments, eg
vector<unsigned char> *fromArray(unsigned char a)
{
vector<unsigned char> *ret = new vector<unsigned char >();
ret->push_back(a);
return ret;
}
vector<unsigned char> *fromArray(unsigned char a, unsigned char b)
{
vector<unsigned char> *ret = new vector<unsigned char >();
ret->push_back(a);
ret->push_back(b);
return ret;
}
But I don’t think I will bother…
You can use a template to deduce the size of any fixed size array:
then
But bear in mind that
auto_ptris deprecated. Preferunique_ptr. Also, note you should not publicly inherit fromstd::vector.