Extract every other element of the vector

Is there a faster way to divide std::vectorinto two half sizes std::vectors(one of which contains values ​​of odd indices, and the other contains values ​​of even indices) than for iterating the original vector and comparing if index%2==0for each index?

+6
source share
3 answers

I'm not sure which means better, but if C ++ 11 you can 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;
}

Watch the online demo at http://ideone.com/pa9rW .

+16
source
// 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());
}

, , . , ..

// 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());
}
+6

old Q by now, but because no one else suggested using iterators and std::next:

// assert myvec.size() % 2 == 0
const unsigned long n = myvec.size() / 2;
std::vector<T> v1(n), v2(n);
std::vector<T>::iterator it = myvec.begin(), i1 = v1.begin(), i2 = v2.begin();
while (it != myvec.end()) {
    v1[*i1] = myvec[*it];
    it = std::next(it);
    i1 = std::next(i1);
    v2[*i2] = myvec[*it];
    it = std::next(it);
    i2 = std::next(i2);
}
0
source

All Articles