Using std::vector as view on to raw memory

后端 未结 10 1612
感动是毒
感动是毒 2021-01-31 13:34

I\'m using a external library which at some point gives me a raw pointer to an array of integers and a size.

Now I\'d like to use std::vector to access and

10条回答
  •  长情又很酷
    2021-01-31 13:50

    Besides the other good suggestion about std::span coming in c++20 and gsl:span, including your own (lightweight) span class until then is easy enough already (feel free to copy):

    template
    struct span {
        T* first;
        size_t length;
        span(T* first_, size_t length_) : first(first_), length(length_) {};
        using value_type = std::remove_cv_t;//primarily needed if used with templates
        bool empty() const { return length == 0; }
        auto begin() const { return first; }
        auto end() const { return first + length; }
    };
    
    static_assert(_MSVC_LANG <= 201703L, "remember to switch to std::span");
    

    Of special note is also the boost range library boost-range if you are interested in the more generic range concept: https://www.boost.org/doc/libs/1_60_0/libs/range/doc/html/range/reference/utilities/iterator_range.html.

    Range concepts will also arrive in c++20

提交回复
热议问题