[ACCEPTED]-Extract every other element of a vector-stdvector
Accepted answer
I am unsure what is meant by better but if C++11 1 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 .
// Make sure the vector is not empty
if(!v.empty()){
for(size_t i = 0; i < (v.size() - 1); i+=2){
v1.push_back(v[i]);
v2.push_back(v[i + 1]);
}
if(v.size() % 2) v1.push_back(v.back());
}
As noted in the comments by multiple people 4 you have to check that the vector is not 3 empty. You could avoid the push back calls 2 by resizing both vectors prior to the loop 1 ie.
// Make sure the vector is not empty
if(!v.empty()){
v1.resize((v.size() + 1) / 2);
v2.resize(v.size() / 2);
for(size_t i = 0, j = 0; i < (v.size() - 1); i+=2, j++){
v1[j] = (v[i]);
v2[j] = (v[i + 1]);
}
if(v.size() % 2) v1.push_back(v.back());
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.