使用std::sort() 依据元素的字段值对容器内元素排序

有一个数据结构Point来描绘一个点,有两个数据成员x, y (都是int), 一个容器对象里边包含着多个Point对象,现在有一个需求就是根据元素x(y)值来重新进行排列。

算法很简单,std::sort() 就可以实现。

首先我们需要提供一个排序规则。这个规则就是一个可调用对象(一个全局函数、类静态成员函数、lambda 表达式(c++11))

调用std::sort(); 

举例说明:

#include <QCoreApplication>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>
#include <QDebug>
 
 
int add(int a, int b) {
    return a + b;
}
 
 
struct Point {
    Point(int x, int y) : x(x),y(y) {}
 
 
    ///[1]指定排序规则
    static bool sToB(Point a, Point b){ return a.y < b.y; }
 
 
    friend QDebug &operator<<(QDebug &outObj, const Point &obj);
    friend bool comp(Point a, Point b);
 
 
private:
    int x;
    int y;
 
 
};
 
 
QDebug &operator<<(QDebug &outObj, const Point& obj) {
    outObj << QString("[%1, %2]").arg(obj.x).arg(obj.y);
    return outObj;
}
 
 
///[1]指定排序规则(或者)
bool comp(Point a, Point b) {
    return a.x < b.x;
}
 
 
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
 
 
    boost::function<int (int, int)> callObj = boost::bind(add, _1, _2);
 
 
    qDebug() << callObj(34, 66);
 
 
    QList<Point> pointList;
    pointList << Point(0, 110) << Point(0, 78) << Point(87, 67) << Point(78, 89);
 
 
    ///param3可以是类静态函数(进行排序 假如是字段为私有时)
    std::sort(pointList.begin(), pointList.end(), Point::sToB);
 
 
    qDebug() << pointList;
 
 
    ///param3可以是全局函数
    std::sort(pointList.begin(), pointList.end(), comp);
    qDebug() << pointList;
 
 
    ///param3还可以是lambda(c++11 支持)
 
 
    return a.exec();
}

猜你喜欢

转载自blog.csdn.net/ypy9323/article/details/78709197