向量连接的 std::make_move_iterator 与 std::move

Ziz*_*Tai 1 c++

(这是关于std::move来自<algorithm>https : //en.cppreference.com/w/cpp/algorithm/move

AFAIK,有两种常见的方法可以将一个向量的内容移动到另一个向量的末尾。

第一的:

std::vector<T> dst, src;
...
dst.insert(dst.end(),
           std::make_move_iterator(src.begin()),
           std::make_move_iterator(src.end()));
Run Code Online (Sandbox Code Playgroud)

第二:

std::vector<T> dst, src;
...
std::move(src.begin(),
          src.end(),
          std::back_inserter(dst));
Run Code Online (Sandbox Code Playgroud)

这些都是进行连接的惯用方法吗?如果是这样,在语义方面有什么区别吗?

Ayx*_*xan 5

两者都应该完成工作,但存在细微差别。当您使用 时insert,向量有机会分配足够的内存以在一次分配中容纳所有元素。当您使用 时back_inserter,这相当于push_back可以进行多次分配和移动的多个s。

  • @AlexShirley 我相信斯科特·迈耶斯(Scott Meyers)在他的一本书中有一个关于此的内容,建议更喜欢“插入”而不是“back_inserter”。这对于OP来说可能是一本很好的读物 (2认同)
  • @AyxanHaqverdili 我搜索了我的收藏,果然 Scott 在有效的 STL 中提到了它 - 特别是在标题为“更喜欢范围成员函数而不是单元素对应函数”的部分中。 (2认同)