数组排序的常规做法就是定义个比较函数然后传进排序函数:
#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;
}