解交织c ++的奇数和偶数项

dan*_*gom 1 c++ vector

是否有一个单线程(或简单的无环路)解决方案来解交织矢量的奇数和偶数条目?
例:

long entries[] = {0,1,2,3,4,5,6,7};
std::vector<long> vExample(entries, entries + sizeof(entries) / sizeof(long) );

vExample.intertwine(vExample.begin(),vExample.end()); // magic one liner I wish existed...

for (int i = 0; i < vExample.size(); i++)
{
    std::cout << vExample[i] << " ";
}
Run Code Online (Sandbox Code Playgroud)

现在我想得到以下输出:

0 2 4 6 1 3 5 7
Run Code Online (Sandbox Code Playgroud)

Bau*_*gen 9

看起来你正在寻找std::partition或者std::stable_partition,取决于你是否需要保留的元素的顺序:

#include <iostream>
#include <algorithm>
#include <vector>

int main () {
    std::vector<int> vals {0,1,2,3,4,5,6,7};
    std::stable_partition(begin(vals), end(vals), [](auto i){return !(i % 2);});
    for (auto v : vals)
        std::cout << v << " ";
}
Run Code Online (Sandbox Code Playgroud)

输出:0 2 4 6 1 3 5 7.现场观看.

您当然可以通过更改谓词来按任何其他标准进行分区.