#include <iostream> #include <vector> #include <algorithm> #include <functional> // std::greater using namespace std; int main() { vector<int> v = {5, 3, 4, 1, 2}; sort(v.begin(), v.end(), greater<int>()); // 使用 std::greater 降序排序 for (const auto& elem : v) ...
我们可以传递“greater()”函数来按降序排序。 #include <bits/stdc++.h>usingnamespacestd;intmain() {intarr[] = {1,5,8,9,6,7,3,4,2,0};intn =sizeof(arr)/sizeof(arr[0]); sort(arr, arr+n, greater<int>()); cout<<" 排序后数组为: \n";for(inti =0; i < n; ++i) cout<...
#include"iostream"using namespace std;#include<vector>#include<algorithm>#include"functional"//函数对象 类重载了()template<typenameT>classCompare{public:booloperator()(T&a,T&b)const{returna<b;}};intmain(){// 创建一个 vector 单端数组容器vector<int>vec;// 向容器中插入元素vec.push_back(9);...
//一般用法(降序) #include<iostream>using namespace std; #include<algorithm>#include<cstdlib>bool compare(int a,int b) { return a>b;//如果改为 return a> n; int a[200]; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a,a+n,compare); for (int i = 0; i < n...
#include<algorithm>#include<vector>#include<functional>std::vector<int>vec; vec.push_back(5); vec.push_back(3); vec.push_back(4);//使用小于运算符进行比较std::sort(vec.begin(), vec.end());//默认行为就是使用小于运算符//或者手工指定小于运算符std::sort(vec.begin(), vec.end(), std...
#include <algorithm>#include <array>#include <functional>#include <iostream>#include <string_view>intmain(){std::array<int,10>s={5,7,4,2,8,6,1,9,0,3};autoprint=[&s](std::string_viewconstrem){for(autoa:s)std::cout<<a<<' ';std::cout<<":"<<rem<<'\n';};std::sort(s...
#include<new> struct foo_t { int size; }; class cmp_t { public: bool operator()(foo_t*a, foo_t*b) { return a->size>= b->size; } }; int main(int argc, char*argv[]) { std::vector<foo_t*> vec; for(int i= 0; i< 17; i++) ...
#include <vector> #include <algorithm> int main(int argc, char const* argv[]) { std::vector<int> vec{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; std::sort(vec.begin(), vec.end(), [](const int& lhs, const int& rhs) { return lhs <= rhs; }); return 0; } tips:...
#include <algorithm>#include <functional>#include <array>#include <iostream>intmain(){std::array<int,10>s={5,7,4,2,8,6,1,9,0,3};// 用默认的 operator< 排序std::sort(s.begin(), s.end());for(autoa:s){std::cout<<a<<" ";}std::cout<<'\n';// 用标准库比较函数对象排序...
// C++ program to demonstrate descending ordersortusing// greater<>().#include<bits/stdc++.h>usingnamespacestd;intmain(){intarr[] = {1,5,8,9,6,7,3,4,2,0};intn =sizeof(arr)/sizeof(arr[0]);sort(arr, arr+n, greater<int>());cout<<"Array after sorting:\n";for(inti =0;...