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

时间:2015-11-18 16:53:42

标签: 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] << " ";
}

现在我希望得到以下输出:

0 2 4 6 1 3 5 7

4 个答案:

答案 0 :(得分:9)

您好像在寻找std::partitionstd::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 << " ";
}

输出:0 2 4 6 1 3 5 7。见live

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

答案 1 :(得分:3)

std::partition(std::begin(vExample), std::end(vExample), [](long l) { return !(l%2); });

当然,partition中有循环。

http://en.cppreference.com/w/cpp/algorithm/partition

答案 2 :(得分:0)

for(int i = 0; i < vExample.size() * 2; i += 2) {
    auto value = vExample[i%vExample.size()];
    //Do whatever you want with value, print it out, etc.
    if(i == vExample.size() - 2) i++;
}

答案 3 :(得分:0)

您可以使用标头std::stable_partition中声明的标准算法<algorithm>。例如

#include <algorithm>

//...

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

std::stable_partition( vExample.begin(), vExample.end(), []( long x ) { return x % 2 == 0; } );

for ( long x : vExample ) std::cout << x << ' ';
std::cout << std::endl;

输出

0 2 4 6 1 3 5 7