Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any alternative to std::dynarray presently available?

Tags:

c++

c++11

c++14

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.

like image 496
Stefano Sanfilippo Avatar asked Jun 25 '13 17:06

Stefano Sanfilippo


3 Answers

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.

like image 149
Mark B Avatar answered Sep 28 '22 18:09

Mark B


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';
}
like image 42
Jon Purdy Avatar answered Sep 28 '22 17:09

Jon Purdy


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:

  • allocator
  • reverse iterator
  • .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).)

like image 42
kennytm Avatar answered Sep 28 '22 17:09

kennytm