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?
If you really need 2 vectors, and you can’t use GMan’s suggestion in the comments:
It’s still O(n), but you can’t do any better than that.
If you need to keep the original vector separate: