Home > database >  Move few elements from list to a vector
Move few elements from list to a vector

Time:11-17

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;
}

CodePudding user response:

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]  

CodePudding user response:

Is it safe to use move_iterator for moving to target And erase the moved section of the source container?

Yes both are true, you can move objects from container and all objects which has been removed become "valid but unspecified state". So, if you want to re-use them, you can assign new values and can use it. If not needed, you can erase them safely.

  • Related