我可以将一个向量的内容移动到另一个向量的末尾吗?

fbr*_*eto 4 stl vector move-semantics c++11

我想做类似以下的事情(a并且b都是vector<my_moveable_type>):

a.insert(a.end(), b.begin(), b.end());
Run Code Online (Sandbox Code Playgroud)

但我希望操作将b元素移动a而不是复制它们.我找到了,std::vector::emplace但这只是一个元素,而不是一个范围.

可以这样做吗?

Nic*_*las 10

您可以使用std::make_move_iterator,以便访问迭代器返回rvalue引用而不是左值引用:

a.insert(a.end(), std::make_move_iterator(b.begin()), std::make_move_iterator(b.end()));
Run Code Online (Sandbox Code Playgroud)


Bla*_*ace 5

有一种std::move似乎可以做你想要的算法.在以下代码中,源代码std::vector为空字符串(向量大小不会更改).

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> one{"cat", "dog", "newt"};
    std::vector<std::string> two;

    std::move(begin(one), end(one), back_inserter(two));

    std::cout << "one:\n";
    for (auto& str : one) {
        std::cout << str << '\n';
    }

    std::cout << "two:\n";
    for (auto& str : two) {
        std::cout << str << '\n';
    }
}
Run Code Online (Sandbox Code Playgroud)

ideone.com上的工作代码

  • @NicolBolas:或者......先调用`one.reserve(one.size()+ two.size());` (2认同)