Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving from a vector with one allocator to a vector with another

Tags:

c++

c++11

vector

I've got a vector<T, alloc> where alloc is a simple wrapper on std::allocator<T> that performs some additional bookkeeping, like counting the number of created objects and such.

Now I want to move from my vector<T, alloc> into vector<T>. None of the vector move functions seems to accept vectors with different allocators.

How can I move data from one vector to another where the allocators are not the same?

like image 573
Puppy Avatar asked Sep 28 '14 08:09

Puppy


People also ask

How do you move a value from one vector to another?

You can't move elements from one vector to another the way you are thinking about; you will always have to erase the element positions from the first vector. If you want to change all the elements from the first vector into the second and vice versa you can use swap. @R.

Can a vector hold multiple data types?

Yes it is possible to hold two different types, you can create a vector of union types. The space used will be the larger of the types.

Can you use a vector as a queue?

You "can" use a vector over a queue, if the queue lifetime is short or if you know the maximum size of your queue.

Does vector have a move constructor?

No. It doesn't call the move constructor. To call move constructor of element you will have to call std::move while pushing to vector itself.


1 Answers

As John Zwinck explains in his answer, you can not move the vector. However, you can move the elements of the vector as follows:

vector<...> u;
...
vector<...> v(
    std::make_move_iterator(u.begin()),
    std::make_move_iterator(u.end())
);

or

vector<...> u;
vector<...> v;
...
v.insert(
    v.end(),
    std::make_move_iterator(u.begin()),
    std::make_move_iterator(u.end())
);

or (suggested by Oktalist)

vector<...> u;
vector<...> v;
...
std::move(u.begin(), u.end(), std::back_inserter(v));
like image 139
Johan Råde Avatar answered Oct 20 '22 02:10

Johan Råde