c++如何对自定义结构体排序

struct内部排序

#include<vector>
#include<algorIThm>
using namespace std;
typedef struct ValuePerWeight //定义结构体
{
    double vw;
    int i;
    bool operator <(const ValuePerWeight &other)const   //升序排序
    {
        return vw>other.vw;
    }
    //或者
    bool operator >(const ValuePerWeight &r)const   //降序排序
    {
        return vw>other.vw;
    }
}ValuePerWeight;
int main(){
    ValuePerWeight a1..an; 
    vector<ValuePerWeight> vpw ;
    for(int i=1;i<=n;i++){
        ....
        vpw.push_back(ai);//对a1到an处理后加到vpw
    }
    sort(vpw.begin(), vpw.end(),greater<ValuePerWeight>());//降序
     
    sort(vpw.begin(), vpw.end(),less<ValuePerWeight>());//升序
    //默认情况为升序 sort(vpw.begin(), vpw.end())
    ....
    return 0;
}
结构体外排序

#include<vector>
#include<algorIThm>
#include <functional> 
 
using namespace std;
 
typedef struct ValuePerWeight//自定义结构体
{
    double vw;
    int i;
     
}ValuePerWeight;
//全局函数
bool a_less_b(const ValuePerWeight& r,const ValuePerWeight& s)
{
    return r.vw < s.vw;
}
bool a_greater_b(const ValuePerWeight& r,const ValuePerWeight& s)
{
    return r.vw > s.vw;
}
int main(){
    ValuePerWeight a1..an; 
    vector<ValuePerWeight> vpw ;
    for(int i=1;i<=n;i++){
        ....
        vpw.push_back(ai);//对a1到an处理后加到vpw
    }
    sort(vpw.begin(), vpw.end(),a_less_b);   //升序排序
     
    sort(vpw.begin(), vpw.end(),a_greater_b); //降序排序
 
    ....
    return 0;
}



你可能感兴趣的:(c++如何对自定义结构体排序)