0

std::vector and std::array store their data in contiguous blocks of memory. Suppose I have

class T;    // A movable class
T t;
std::vector<T>  vec;
vec.push_back(t);

std::array<T,1> arr;

Assuming like above that I am guaranteed to know that vec and arr have the same length. Is there a way that I can move vec to array instead of copy it with std::copy(vec.begin(), vec.end(), arr.begin())?

3
  • 3
    std::span (C++20) might interest you. Commented Jun 30, 2021 at 11:33
  • This migth be an XY problem. Could you specify what problem you are trying to solve with that. Commented Jun 30, 2021 at 11:47
  • Note that you cannot move objects in C++. You can only move their content. An array will always have its own objects-elements and a vector also its own, and both will be distinct. You cannot make the vector elements to be owned/managed by an array object. Span might be a solution as suggested (but we don't know what is the use case). Commented Jun 30, 2021 at 11:51

2 Answers 2

11

You cannot move the vector. But you can move each element of the vector:

std::move(vec.begin(), vec.end(), arr.begin());
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, true indeed. And useful if T is big. Have an upvote.
But if elements are T as in my example instead of T* or T& how would that work without copying?
"But if elements are T as in my example instead of T* or T& how would that work without copying?" I think that if T does have a move contructor / operator implemented properly, then it should avoid copying.
@ReimundoHeluani you can't have a container of references. Pointers are moved/copied like other objects.
4

Alas not. Neither std::vector nor std::array have a mechanism to attach a block of memory, or to detach a block of memory.

std::copy is possibly the most reliable method.

2 Comments

std::copy this C++ standard draft.
i think it is more than that. A simple picture of a std::vector is just a pointer to dynamically allocated memory, while a std::array is an array. You also cannot assign contents of a vector to a T[N]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.