How can I initialize an std::array
from a range (as defined by a pair of iterators)?
Something like this:
vector<T> v;
...
// I know v has exactly N elements (e.g. I just called v.resize(N))
// Now I want a initialized with those elements
array<T, N> a(???); // what to put here?
I thought array
would have a constructor taking a pair of iterators, so that I could do array<T, N> a(v.begin(), v.end())
, but it appears to have no constructors at all!
I know I can copy
the vector into the array, but I'd rather initialize the array with the vector contents directly, without default-constructing it first. How can I?
You can use
BOOST_PP_ENUM
as:Here, the last line is expanded as:
which is what you want.
With random access iterators, and assuming a certain size at compile-time, you can use a pack of indices to do so:
This assumes a compiler capable of eliding the intermediate copies. I think that assumption is not a big stretch.
Actually, it can be done with input iterators as well, since the computation of each element in a braced-init-list is sequenced before the computation of the next element (§8.5.4/4).
Since
*first++
doesn't have anyI
in it, we need a dummyI
to provoke the pack expansion. Comma operator to the rescue, withvoid()
to silence warnings about lack of effects, and also preventing overloaded commas.Like you have noticed, std::array has no constructors at all (except for the compiler generated default constructor).
This was done on purpose, so it can be statically initialized just like a C array. If you want to fill the array without a static initializer, you will have to copy your data.