Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create std::vector in-place from raw data

Given a raw array of elements, how to create a std::vector that takes ownership of the raw array without reallocate & copy?

For example having the raw array:

int* elems = new int[33]

how to create a std::vector of size 33 pointing to elems?

I am sure that theoretically this is possible, as usually std::vector is implemented as a structure containing three pointers, one pointing to the beginning of the allocated memory, one to the end of the valid elements, and one to the end of the allocated memory. But is there a standard way of initializing the std::vector structure with the raw array?

like image 377
cDc Avatar asked Nov 11 '17 09:11

cDc


1 Answers

What you need is a "view" rather than a container. Containers own their elements and their main purpose is to encapsulate the raw memory they manage. If you need to manage the memory yourself then you dont need a container. Take a look at string_view that would be your solution if you had a string. Perhaps boost ranges is something that you could apply. From the docs (emphasize mine):

The motivation for the Range concept is that there are many useful Container-like types that do not meet the full requirements of Container, and many algorithms that can be written with this reduced set of requirements. In particular, a Range does not necessarily

  • own the elements that can be accessed through it,
  • have copy semantics,

PS: Actually std::array_view was considered for C++17, but unfortunately it didnt make it into the standard.

like image 70
463035818_is_not_a_number Avatar answered Sep 21 '22 02:09

463035818_is_not_a_number