简体   繁体   中英

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

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 vector s with different allocators.

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

This is indeed a weird thing about the STL. You will need to insert() the values of your source vector into your destination vector. Or you can use one of the several alternate-universe STL implementations which address this issue directly, for example:

Some of the folks who made the above quasi-STL implementations tried to get their allocator model changes adopted into the C++ standard, but they were not successful.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM