i have to use std::sort() to sort numbers in an array like this:
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::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}.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.