Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract every other element of a vector

Tags:

c++

stdvector

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?

like image 698
user1504193 Avatar asked Aug 22 '12 14:08

user1504193


1 Answers

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 .

like image 87
hmjd Avatar answered Oct 05 '22 22:10

hmjd