Is it possible to move std :: array to std :: vector?

This is a question about the interaction of stack memory and heap memory and the specific case of transition from stack to heap through std::arrayand classes std::vector.

In principle, std::array<T>it can be considered as a pointer to the first elements, as well as some compilation time information about the size of the array. Is it possible to have a constructor std::vector<T>that takes this fact into account and tries to move the contents arrayto vectorby simply copying the pointer.

A use case would be that it has a function that returns std::array<double, >

std::array<double, 20> fun(){...};

but later it is decided to assign it std::vectorwithout having to copy an element by element.

std::vector<double> v = fun(); // not working code

Now need to do

std::array<double, 20> tmp = fun();
std::vector<double> v(tmp.begin(), tmp.end());

, , std::vector<double> v(std::move(tmp)); \\ not working code.

std::vector std::array , .

, , std::array , std::vector . , std::vector, .

, , :

( ), ?

std::vector std::array?

MWE:

#include<array>
#include<vector>

std::array<double, 20> fun(){return {};} // don't change this function

int main(){
    std::array<double, 20> arr = fun(); // ok
    std::vector<double> v(arr.begin(), arr.end()); // ok, but copies and the allocation is duplicated
    std::vector<double> v2 = fun(); // not working, but the idea is that the work is not duplicated
}
+4
2

( ), ?

" ". . - , , .

, , . ", " - "" .

:

|                      |
|----------------------|
| stack block 1        |
|----------------------|
| your vector          |
|----------------------|
| stack block 2        |
|----------------------|
|-                    -|

, 2, 1. , .

, - . , . , , , , .

, . , , , .

+3

, std::vector std::array , , .

std::vector . , , . , , , .. , , .

, std::vector std::move_iterator, std::array. , , , , :

std::array<BigThing, 20> a = fun();
std::vector<BigThing> b { std::make_move_iterator(a.begin()),
                          std::make_move_iterator(a.end())) };
+6

Source: https://habr.com/ru/post/1618099/


All Articles