STL中sort函数用法

sort()头文件是:#include <algorithm>

sort()函数用法有很多种,重载运算符,定义比较函数。

我们重载>和<运算符就能够运用less,greater,less_equal进行比较排序。

也可以定义比较函数。

Point.h

#ifndef POINT_H
#define POINT_H


class Point
{
    private:
        double x;
        double y;
    public:
        Point();
        Point(double x1, double y1);
        void Setter(double x1, double y1);
        bool operator>(const Point& b)const;
        bool operator<(const Point& b)const;
        void show()const;
        virtual ~Point();
    protected:

};

#endif // POINT_H


Point.cpp
#include "Point.h"
#include <iostream>
using namespace std;
Point::Point()
{
    //ctor
}
Point::Point(double x1, double y1)
{
   x = x1, y = y1;
}
bool Point::operator>(const Point& b) const
{
    return x > b.x || y > b.y;
}
bool Point::operator<(const Point& b) const
{
    return x < b.x || y < b.y;
}

void Point::Setter(double x1, double y1)
{
    x = x1, y = y1;
}
void Point::show()const
{
    cout << x <<" "<< y << endl;
}
Point::~Point()
{
    //dtor
}


main.cpp
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <vector>
#include "Point.h"
using namespace std;

bool cmp_less(const Point& a, const Point& b)
{ //升序排列
    return a.x < b.x || a.y < b.y;
}

bool cmp_greater(const Point& a, const Point& b)
{//降序排列
    return a.x > b.x || a.y > b.y;
}
int main()
{
    Point a[10];
    for (int i = 0; i < 10; i ++) {
        a[i].Setter(i, i);
    }
    sort(a, a+10,less<Point>());//升序排列
    for (int i = 0; i < 10; i ++) {
        a[i].show();
    }
    cout <<endl;
    sort(a, a+10,greater<Point>());//降序排列
    for (int i = 0; i < 10; i ++) {
        a[i].show();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值