C++如何将含1、2、3的数组按2优先、其次1、最后3的顺序排序
实现方法
你可以通过给std::sort传入自定义比较规则来实现需求,你的排序优先级为2 > 1 > 3,只需要在比较函数中定义对应权重逻辑即可。
以下是修改后的完整代码:
#include <iostream> #include <algorithm> #include <cstdlib> using namespace std; // 自定义比较函数 bool customCompare(int a, int b) { // 给每个数值定义排序权重,权重越小越靠前 auto getPriority = [](int num) { if (num == 2) return 0; if (num == 1) return 1; return 2; // 3的权重最大排最后 }; return getPriority(a) < getPriority(b); } int main() { int size; cin >> size; int *array = new int [size]; for(int i = 0; i < size; i++) { array[i] = rand() % 3 + 1; } // 传入自定义比较函数 std::sort(array, array + size, customCompare); for(int i = 0; i < size; i++) { cout << array[i] << endl; } // 释放动态申请的内存,避免泄漏 delete[] array; return 0; }
逻辑说明
- 我们给每个待排序的数值映射了权重:2对应权重0(最高优先级,排最前)、1对应权重1(中间优先级)、3对应权重2(最低优先级,排最后)
- 比较两个数时,权重小的数排在前面,刚好匹配你需要的排序效果
- 如果你使用的是C++11及以上版本,也可以直接把比较逻辑写成lambda直接传入
std::sort,不需要单独声明函数:
std::sort(array, array + size, [](int a, int b) { auto getPrio = [](int n) { return n == 2 ? 0 : (n == 1 ? 1 : 2); }; return getPrio(a) < getPrio(b); });
内容的提问来源于stack exchange,提问作者erwyyy
相关产品推荐
相关产品推荐

