STL中sort函数用法

来源:互联网 发布:js对象转数组 编辑:程序博客网 时间:2024/06/01 10:28

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

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

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

也可以定义比较函数。

Point.h

#ifndef POINT_H#define POINT_Hclass 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