C++自定义排序
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
bool compare1(const int& a, const int& b)
{
return a < b;
}
bool compare2(const int& a, const int& b)
{
return a > b;
}
bool compare3(const int& a, const int& b)
{
string sa = to_string(a);
string sb = to_string(b);
return stoi(sa+sb) < stoi(sb+sa);
}
int main(int argc, char* argv[])
{
vector<int> nums{2, 4, 7, 1, 9, 3};
sort(nums.begin(), nums.end());
for (auto num : nums)
cout << num << " ";
cout << endl;
vector<int>{2, 4, 7, 1, 9, 3}.swap(nums);
sort(nums.begin(), nums.end(), compare1);
for (auto num : nums)
cout << num << " ";
cout << endl;
vector<int>{2, 4, 7, 1, 9, 3}.swap(nums);
sort(nums.begin(), nums.end(), compare2);
for (auto num : nums)
cout << num << " ";
cout << endl;
vector<int>{23, 4, 12, 34, 123}.swap(nums);
sort(nums.begin(), nums.end(), compare3);
for (auto num : nums)
cout << num << " ";
cout << endl;
return 0;
}
class Solution
{
public:
static bool compare(const int& a, const int& b)
{
return a > b;
}
void fun(){
sort(vec.begin(), vec.end(), &Solution::compare);
}
private:
std::vector<int> vec;
};