gpt4 book ai didi

c++ - 对偶数进行升序排序,然后对奇数进行降序排序

转载 作者:行者123 更新时间:2023-11-30 01:41:04 25 4
gpt4 key购买 nike

我必须使用 std::sort() 对数组中的数字进行排序,如下所示:

偶数先升后奇数降

到目前为止我得到了:

#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);

}

但我想不出正确的顺序算法来这样做

最佳答案

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;
}

关于c++ - 对偶数进行升序排序,然后对奇数进行降序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com