数组排序的常规做法就是定义个比较函数然后传进排序函数: #include <algorithm> #include <iostream> #include <vector> using namespace std; int main(int argc, char* argv[]) { vector<int> nums = {2, 3, 5, 7, 11, 13, 15, 17}; sort(nums.begin(), nums.end(), [](int x, int y) { int units_x = x % 10; int units_y = y % 10; if (units_x == units_y) return x < y; return units_x < units_y; }); for (int x : nums) cout << x << " "; cout << endl; return 0; }不过这里个位数的值只有0-9一共10种,所以像楼上一样分到10个vector中排序,然后依次汇总应该才是题目想要的做法,毕竟给定的数组是有序的,这个条件在之前的代码里没利用: #include <assert.h> #include <algorithm> #include <array> #include <iostream> #include <vector> using namespace std; int main(int argc, char* argv[]) { // nums为有序数组 vector<int> nums = {2, 3, 5, 7, 11, 13, 15, 17}; array<vector<int>, 10> buckets; // TODO: use array<forward_list, 10> may be better? for (int x : nums) buckets[x % 10].emplace_back(x); size_t index = 0; for (const auto& v : buckets) { for (int x : v) { assert(index < nums.size()); nums[index++] = x; } } for (int x : nums) cout << x << " "; cout << endl; return 0; }
点赞 11

相关推荐

04-15 20:51
门头沟学院 Java
纳斯卡可:把名字改一下吧 千万级用户你真测过吗
点赞 评论 收藏
分享
一只代码牛:应该不是你的问题,我感觉应该是最近不缺人
我的求职进度条
点赞 评论 收藏
分享
05-23 19:33
重庆大学 Java
只学了传统后端,马上去后端实习了,在想要不要学习agent开发相关的。27秋招和26相比难度如何?
我连备胎都不是却还在...:就暑期实习而言,大厂官宣hc 比 26 多,但是我观察看应该低于 26 的,估计秋招也不简单
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务