Is there a faster way of splitting a std::vector
in to two half-size std::vectors
(one containing values of the odd indices and the other containing values of even indices) than to iterate through the original vector and compare if index%2==0
for each index?
I am unsure what is meant by better but if C++11 you could use std::partition_copy:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
std::vector<int> v1;
for (int i = 0; i < 100; i++) v1.push_back(i);
std::vector<int> v2;
std::vector<int> v3;
bool toggle = false;
std::partition_copy(v1.begin(),
v1.end(),
std::back_inserter(v2),
std::back_inserter(v3),
[&toggle](int) { return toggle = !toggle; });
std::cout << v2.size() << "\n";
std::cout << v3.size() << "\n";
return 0;
}
See online demo http://ideone.com/pa9rW .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With