Using std::vector as view on to raw memory

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

    Now I'd like to use std::vector to access and modify these values in place

    You cannot. That's not what std::vector is for. std::vector manages its own buffer, which is always acquired from an allocator. It never takes ownership of another buffer (except from another vector of same type).

    On the other hand, you also don't need to because ...

    The reason is that I need to apply algorithms from (sorting, swaping elements etc.) on that data.

    Those algorithms work on iterators. A pointer is an iterator to an array. You don't need a vector:

    std::sort(data, data + size);
    

    Unlike function templates in , some tools such as range-for,std::begin/std::end and C++20 ranges do not work with just a pair of iterators though, while they do work with containers such as vectors. It is possible to create a wrapper class for iterator + size that behaves as a range, and works with these tools. C++20 will introduce such wrapper into the standard library: std::span.

提交回复
热议问题