Using std::vector as view on to raw memory

后端 未结 10 1572
感动是毒
感动是毒 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:55

    C++20's std::span

    If you are able to use C++20, you could use std::span which is a pointer - length pair that gives the user a view into a contiguous sequence of elements. It is some sort of a std::string_view, and while both std::span and std::string_view are non-owning views, std::string_view is a read-only view.

    From the docs:

    The class template span describes an object that can refer to a contiguous sequence of objects with the first element of the sequence at position zero. A span can either have a static extent, in which case the number of elements in the sequence is known and encoded in the type, or a dynamic extent.

    So the following would work:

    #include 
    #include 
    #include 
    
    int main() {
        int data[] = { 5, 3, 2, 1, 4 };
        std::span s{data, 5};
    
        std::sort(s.begin(), s.end());
    
        for (auto const i : s) {
            std::cout << i << "\n";
        }
    
        return 0;
    }
    

    Check it out live

    Since std::span is basically pointer - length pair, you can use in a following manner too:

    size_t size = 0;
    int *data = get_data_from_library(size);
    std::span s{data, size};
    

    Note: Not all compilers support std::span. Check compiler support here.

    UPDATE

    If you are not able to use C++20, you could use gsl::span which is basically the base version of the C++ standard's std::span.

    C++11 solution

    If you are limited to C++11 standard, you can try implementing your own simple span class:

    template
    class span {
       T* ptr_;
       std::size_t len_;
    
    public:
        span(T* ptr, std::size_t len) noexcept
            : ptr_{ptr}, len_{len}
        {}
    
        T& operator[](int i) noexcept {
            return *ptr_[i];
        }
    
        T const& operator[](int i) const noexcept {
            return *ptr_[i];
        }
    
        std::size_t size() const noexcept {
            return len_;
        }
    
        T* begin() noexcept {
            return ptr_;
        }
    
        T* end() noexcept {
            return ptr_ + len_;
        }
    };
    

    Check out C++11 version live

提交回复
热议问题