“move” two vectors together

前端 未结 2 1179
遥遥无期
遥遥无期 2020-12-23 18:29

If I have two vectors and want to combine them to one, I can do it the following way:

std::vector a(100); // just some random size here
std::vector&         


        
2条回答
  •  情话喂你
    2020-12-23 19:09

    Yes, use std::move:

    #include 
    std::move(b.begin(), b.end(), std::back_inserter(a));
    

    Alternatively, you can use move iterators:

    a.insert(a.end(),
             std::make_move_iterator(b.begin()), std::make_move_iterator(b.end()));
    

    Remember to #include in both cases, and before you begin, say:

    a.reserve(a.size() + b.size());
    

    Depending on the cost of value-initialization compared to checking and incrementing the size counter, the following variant may also be interesting:

    std::size_t n = a.size();
    a.resize(a.size() + b.size());
    std::move(b.begin(), b.end(), a.begin() + n);
    

提交回复
热议问题