假设我有一个 std::vector<T> from
和 std::vector<T> to
哪儿 T
是一个不可复制但可移动的类型,而 to
可能是空的,也可能不是。我希望所有元素都在 from
后附 to
.
如果我使用 std::vector<T>::insert(const_iterator pos, InputIt first, InputIt last)
超载 pos = to.end()
它将试图 拷贝 所有对象。
现在,如果 to.empty()
我可以只是 std::move(from)
否则我可以先 from.reserve(from.size()+to.size())
然后手动 to.emplace_back(std::move(from[i]))
每一个元素 from
最后 from.clear()
.
有没有一种直接的方法可以用一个 std
方便函数还是包装器?
insert
可以很好地与 std::move_iterator 和 std::make_move_iterator 助手功能。
to.insert(to.end(),std::make_move_iterator(from.begin()),
std::make_move_iterator(from.end()));
#include<iterator>
std::vector<T> source = {...};
std::vector<T> destination;
std::move(source.begin(), source.end(), std::back_inserter(destination));
你可能要考虑 std::move()
算法 - 即,移动的对应物为 std::copy()
- 而非 std::move()
方便模板功能。
#include <vector>
#include <algorithm>
struct OnlyMovable {
OnlyMovable() = default;
OnlyMovable(const OnlyMovable&) = delete;
OnlyMovable(OnlyMovable&&) = default;
};
auto main() -> int {
std::vector<OnlyMovable> from(5), to(3);
std::move(from.begin(), from.end(), std::back_inserter(to));
}