Using std::vector as view on to raw memory

后端 未结 10 1692
感动是毒
感动是毒 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 14:03

    You can't do this with a std::vector without making a copy. std::vector owns the pointer it has under the hood and allocates space through the allocator that is provided.

    If you have acess to a compiler that has support for C++20 you could use std::span which was built for exactly this purpose. It wraps a pointer and size into a "container" that has the C++ container interface.

    If not, you can use gsl::span which is what the standard version was based off of.

    If you don't want to import another library you could trivially implement this yourself depending on what all functionality you want to have.

提交回复
热议问题