c std::vector splitting into two

16,385

If you really need 2 vectors, and you can't use GMan's suggestion in the comments:

// where v1 is your original vector
std::vector<T> v2(
    std::make_move_iterator(v1.begin() + v1.size()/2),
    std::make_move_iterator(v1.end()));
v1.erase(v1.begin() + v1.size()/2, v1.end());

It's still O(n), but you can't do any better than that.

If you need to keep the original vector separate:

std::vector<T> v2(v1.begin(), v1.begin() + v1.size()/2),
               v3(v1.begin() + v1.size()/2, v1.end());
Share:
16,385
user1855952
Author by

user1855952

Student in the UK

Updated on July 19, 2022

Comments

  • user1855952
    user1855952 almost 2 years

    Is there an easy and run-time efficient way to take a std::vector<> in c++ and split it in half into two other vectors?

    Because right now I'm doing this:

    std::vector<> v1, v2;
    for(int i = 0; i < vector.size(); i++)
    {
        if(i < vector.size()/2) v1.push_back(vector[i]);
        else v2.push_back(vector[i]);
    }
    

    which runs in O(n) time and this is an operation I have to perform quite frequently. So is there a better way?

  • user1855952
    user1855952 over 11 years
    Why do you need the v1.end() in the second parameter for both calls?
  • Benjamin Lindley
    Benjamin Lindley over 11 years
    @user1855952: It designates the end of the range which you which you want to copy or erase, whatever the case may be.
  • Jonathan Wakely
    Jonathan Wakely over 11 years
    You could improve this by using std::make_move_iterator(v1.begin()) and std::make_move_iterator(v1.end()) to fill v2
  • Benjamin Lindley
    Benjamin Lindley over 11 years
    @JonathanWakely: Good call. Done.