Search code examples
c++move-semantics

Move few elements from list to a vector


I am planning to move some elements from a list to the target container(say vector) for further processing. Is it safe to use move_iterator for moving to target And erase the moved section of the source container?

#include<list>
#include<vector>
#include<iterator>
struct DataPoint {};
int main() {
    std::list<Datapoint> d_data; // source
    std::vector<Datapoint> v2;   // target
    v2.insert(v2.end(), 
              std::make_move_iterator(d_data.begin()), 
              std::make_move_iterator(d_data.begin() + size)
             );
    d_data.erase(d_data.begin(), d_data.begin() + size);  // safe? necessary?
    //...
    //d_batch->addData(v2);
    return 0;
}

Solution

  • You may find std::move easier to use.

    And yes, you do need to erase the moved elements in the source container.

    [Demo]

    #include <algorithm>  // move
    #include <fmt/ranges.h>
    #include<list>
    #include<vector>
    #include<iterator>  // back_inserter
    
    int main() {
        std::list<int> l{1, 2, 3, 4, 5};  // source
        std::vector<int> v;  // target
        auto begin_it{std::next(l.begin())};
        auto end_it{std::prev(l.end())};
        std::move(begin_it, end_it, std::back_inserter(v));
        fmt::print("l before erase: {}\n", l);
        l.erase(begin_it, end_it);
        fmt::print("l after erase: {}\nv: {}\n", l, v);
    }
    
    // Outputs:
    //
    //   l before erase: [1, 2, 3, 4, 5]
    //   l after erase: [1, 5]
    //   v: [2, 3, 4]