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());
Comments
-
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 over 11 yearsWhy do you need the v1.end() in the second parameter for both calls?
-
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 over 11 yearsYou could improve this by using
std::make_move_iterator(v1.begin())
andstd::make_move_iterator(v1.end())
to fillv2
-
Benjamin Lindley over 11 years@JonathanWakely: Good call. Done.