[英]sort even numbers ascending then odd numbers descending
i have to use std::sort() to sort numbers in an array like this: 我必须使用std :: sort()对数组中的数字进行排序,如下所示:
even numbers ascending and then odd numbers descending 偶数升序,然后奇数降序
so far i got: 到目前为止,我得到了:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool order(int a, int b)
{
if (a % 2 == 0)
{
return a < b;
}
else if(a % 2 != 0)
{
return b < a;
}
}
int main()
{
std::vector<int> v = { 2, 3, 5, 6, 4, 1 };
std::sort(v.begin(), v.end(), order);
}
but i cant figure out the correct order algorithm to do so 但我不能找出正确的顺序算法来做到这一点
if (a % 2 == b % 2) { // same parity
if (a % 2) { // odd descending
return b < a;
} else { // even ascending
return a < b;
}
} else { // odd is bigger than even
return b % 2;
}
With std: 使用std:
std::vector<int> v {2, 3, 5, 6, 4, 1};
auto it = std::partition(v.begin(), v.end(), [](int e) { return e % 2 == 0; });
std::sort(v.begin(), it);
std::sort(it, v.end(), std::greater<>{});
// `v` would be now { 2, 4, 6, 5, 3, 1}.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.