C++11 gave us great std::array
, which requires size to be known at compile time:
std::array<int, 3> myarray = {1, 2, 3};
Now, I happen to have some old short*
buffers to wrap, whose size will be known (and it will be, of course) at runtime only.
C++14 will define std::dynarray
to cover this case, but dynarray
is not available yet in GCC 4.7 nor in Clang 3.2.
So, does anyone know a container which is comparable to std::array
(in terms of efficiency) but does not require to specify size at compile time? I suspect Boost has something ready for me, although I couldn't find anything.
I think std::vector
is what you're looking for before dynarray
becomes available. Just use the allocating constructor or reserve
and you'll avoid reallocation overhead.
I’ll put in a vote for std::unique_ptr<short[]>(new short[n])
if you don’t need the range-checked access provided by std::dynarray<T>::at()
. You can even use an initializer list:
#include <iostream>
#include <memory>
int main(int argc, char** argv) {
const size_t n = 3;
std::unique_ptr<short[]> myarray(new short[n]{ 1, 2, 3 });
for (size_t i = 0; i < n; ++i)
std::cout << myarray[i] << '\n';
}
You could (ab)use a std::valarray<short>
.
int main() {
short* raw_array = (short*) malloc(12 * sizeof(short));
size_t length = 12;
for (size_t i = 0; i < length; ++ i) {
raw_array[i] = (short) i;
}
// ...
std::valarray<short> dyn_array (raw_array, length);
for (short elem : dyn_array) {
std::cout << elem << std::endl;
}
// ...
free(raw_array);
}
valarray
supports most features of a dynarray
, except:
.at()
.data()
Note that the standard (as of n3690) does not require valarray
storage be continuous, although there's no reason not to do so :).
(For some implementation detail, in libstdc++ it is implemented as a (length, data) pair, and in libc++ it is implemented as (begin, end).)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With