栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ qt中的sort函数详解

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ qt中的sort函数详解

sort函数是用来排序的,排序的数据类型可以是内置数据类型,也可以是自定义的数据类型,这是一个重载函数,可以有两个参数,也可以有三个参数,这里主要讲解它的第三个参数,它的第三个参数可以自定义排序规则,结合下面的代码讲解:

一..h文件:

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
struct Person
{
    QString name;
    int workAge;
};
class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();


private:
    Ui::Widget *ui;
    QListm_PersonList;
};
#endif // WIDGET_H
bool Cmp(Person p1,Person p2);

 这里特别注意一下,为什么将sort的第三个参数,也就是数据的自定义比较数据的函数放在类的外面,这是因为我们没有通过类对象来调用函数,这种情况下我们可以在类中声明,在类外定义,写成静态函数,也可以直接声明和定义都在类的外面,我尝试用了第二种方法。

二..cpp文件 

1.两个参数的时候:

#include "widget.h"
#include "ui_widget.h"
#include 
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //没有第三个参数
    QList vec;
    for (int i =10;i>=1;i--)
    {
        vec.append(i);
    }
    qDebug()<<"原始数据";
    for (int j =0;j());
    for (int j =0;j 

2.有三个参数的时候:

#include "widget.h"
#include "ui_widget.h"
#include 
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //自定义数据类型,自定义第三个函数,自定义比较含义
    //..自定义数据类型初始化
    Person myPerson1;
    Person myPerson2;
    Person myPerson3;
    Person myPerson4;
    Person myPerson5;
    myPerson1.name = "one";
    myPerson1.workAge = 1;
    myPerson2.name ="two";
    myPerson2.workAge = 2;
    myPerson3.name ="three";
    myPerson3.workAge = 3;
    myPerson4.name ="four";
    myPerson4.workAge = 4;
    myPerson5.name ="five";
    myPerson5.workAge = 5;
    m_PersonList.append(myPerson1);
    m_PersonList.append(myPerson2);
    m_PersonList.append(myPerson3);
    m_PersonList.append(myPerson4);
    m_PersonList.append(myPerson5);
    qDebug()<<"自定义数据排序之前:";
    for (int i =0;ip2.workAge;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/890247.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号