本文介绍了按偶数和奇数索引对向量进行排序.C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个单行(或简单的无循环)解决方案来按偶数和奇数索引对向量进行排序?示例:
Is there a one liner (or a simple loop-free) solution to sort a vector by its even and odd indices?Example:
long entries[] = {0,1,2,10,11}; // indices 0 1 2 3 4
std::vector<long> vExample(entries, entries + sizeof(entries) / sizeof(long) );
vExample.sortEvenOdd(vExample.begin(),vExample.end()); // magic one liner I wish existed...
for (int i = 0; i < vExample.size(); i++)
{
std::cout << vExample[i] << " ";
}
现在我想有以下输出:
0 2 11 1 10 // corresponding to indices 0 2 4 1 3
推荐答案
我试着做一个真正的one liner:
std::stable_partition(std::begin(input), std::end(input),
[&input](int const& a){return 0==((&a-&input[0])%2);});
这里是完整的程序:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> input {0,1,2,10,11};
std::stable_partition(std::begin(input), std::end(input),
[&input](int const& a){return 0==((&a-&input[0])%2);});
for (auto v : input)
std::cout << v << " ";
}
好吧,我知道,它之所以起作用的唯一原因是 vector 使用了一组连续的项目,而整个事情都很脏……但因为这是 OP 要求的单衬,它不需要任何额外的东西提升...
Ok I know, it works for the sole reason that vector uses a contiguous array of items and the whole thing is dirty... But for that's a one liner as asked by the OP and it doesn't require anything extra like boost...
这篇关于按偶数和奇数索引对向量进行排序.C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!