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:
The Bloomberg Basic Development Environment (BDE) STL has a runtime polymorphic allocator described here: https://github.com/bloomberg/bde/wiki/BDE-Allocator-model . It's open source at the same site.
The Electronic Arts STL, described here: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html with source online here: https://github.com/paulhodge/EASTL
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.