How can I move the contents of std::vector
into an array safely without copying or iterating over all elements?
void someFunc(float* arr, std::size_t& size)
{
std::vector<float> vec(5, 1.5f);
// do something with the data
size = vec.size();
arr = vec.data(); // this doesn't work, as at the end of the function the data in std::vector will be deallocated
}
main()
{
float* arr;
std::size_t size{0};
someFunc(arr, size);
// do something with the data
delete [] arr;
}
How can I assign my array with the data in std::vector
and making sure that deallocation will not be called on std::vector
? Or maybe any other ideas to go around this?
The elements of a vector are contiguous. Otherwise, you just have to copy each element: double arr[100]; std::copy(v. begin(), v.
Yes. Assuming v. size() > 0 , this is safe (If the vector is empty, then v[0] results in undefined behavior). The elements of a std::vector container are stored contiguously, just like in an ordinary array.
std::array is movable only if its contained objects are movable. std::array is quite different from the other containers because the container object contains the storage, not just pointers into the heap. Moving a std::vector only copies some pointers, and the contained objects are none the wiser.
You can't.
A vector owns its buffer. You cannot steal it.
You will have to copy/move the elements individually, optionally using a helper algorithm that does the iteration for you (std::copy
/std::move
).
(Also note that, since your element type is just float
, a move here is a copy.)
(Also note that this std::move
, the algorithm, is not the same as std::move
, the rvalue cast.)
Consider whether you really need to do this. You can treat the vector's data as an array using vec.data()
whenever you need to, as long as you keep the vector alive. Surely that's better than sacrificing RAII?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With