Is there a standard way of moving a range into a vector?

后端 未结 2 1696
梦谈多话
梦谈多话 2020-12-01 03:25

Consider the following program which inserts a range of elements into a vector:

vector v1;
vector v2;

v1.push_back(\"one\");
v1.         


        
相关标签:
2条回答
  • 2020-12-01 04:03
    1. std::move algorithm with preallocation:

      #include <iterator>
      #include <algorithm>
      
      v1.reserve(v1.size() + v2.size()); // optional
      std::move(v2.begin(), v2.end(), std::back_inserter(v1));
      
    2. The following would be more flexible yet:

      v1.insert(v1.end(), 
           std::make_move_iterator(v2.begin()), 
           std::make_move_iterator(v2.end()));
      

      Steve Jessop provided background information on precisely what it does and probably how it does so.

    0 讨论(0)
  • 2020-12-01 04:05

    You use a move_iterator with insert:

    v1.insert(v1.end(), make_move_iterator(v2.begin()), make_move_iterator(v2.end()));
    

    The example in 24.5.3 is almost exactly this.

    You'll get the optimization you want if (a) vector::insert uses iterator-tag dispatch to detect the random-access iterator and precalculate the size (which you've assumed it does in your example that copies), and (b) move_iterator preserves the iterator category of the iterator it wraps (which is required by the standard).

    On an obscure point: I'm pretty sure that vector::insert can emplace from the source (which is irrelevant here, since the source is the same type as the destination, so an emplace is the same as a copy/move, but would be relevant to otherwise-identical examples). I haven't yet found a statement that it's required to do so, I've just inferred it from the fact that the requirement on the iterator pair i,j passed to insert is that T be EmplaceConstructible from *i.

    0 讨论(0)
提交回复
热议问题