Search code examples
c++c++11c++14

Any alternative to std::dynarray presently available?


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.


Solution

  • 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).)