QList用法详解(Qt中的QList类详解)

一、QList概述

QList是Qt框架中的一个容器类,用来存储一组数据。它可以存储各种数据类型,比如整数、字符串、结构体等等。同一份代码可以在不同的平台上编译运行,保证了代码的可移植性。

二、QList的基本使用

1、定义和初始化列表

QList使用模板类的形式来定义,语法如下:

QList<类型> list;

其中“<类型>”表示我们要存储的数据类型。例如,存储整数类型的列表:

QList<int> list;

定义列表之后,我们可以使用一些初始化方法来给列表填入数据。

最简单的初始化方法是使用集合初始化,例如:

QList<int> list = {1, 2, 3, 4, 5};

除此之外,还可以使用push_back()方法来插入数据,例如:

QList<int> list;
list.push_back(1);
list.push_back(2);
list.push_back(3);

2、元素的访问

QList提供了多种访问元素的方法,例如使用下标访问:

QList<int> list = {1, 2, 3, 4, 5};
int num = list[2]; // num等于3

除了使用下标访问,还可以使用at()方法访问:

QList<int> list = {1, 2, 3, 4, 5};
int num = list.at(2); // num等于3

如果我们要获取第一个元素和最后一个元素,可以使用front()和back()方法:

QList<int> list = {1, 2, 3, 4, 5};
int first = list.front(); // first等于1
int last = list.back(); // last等于5

3、元素的修改和删除

QList提供了多种修改元素和删除元素的方法,例如使用下标修改元素:

QList<int> list = {1, 2, 3, 4, 5};
list[2] = 10;

使用remove()方法删除元素:

QList<int> list = {1, 2, 3, 4, 5};
list.remove(2); // 删除第3个元素,list变为{1, 2, 4, 5}

三、QList的高级用法

1、迭代器

QList提供了多种迭代器来访问列表中的元素,例如:

QList<int> list = {1, 2, 3, 4, 5};
QList<int>::iterator it;
for (it = list.begin(); it != list.end(); ++it) {
    // 使用it访问当前元素,例如:int num = *it;
}

其中,begin()和end()方法分别返回列表的首元素迭代器和尾元素迭代器。

2、排序

QList提供了sort()方法来对列表中的元素进行排序,例如:

QList<int> list = {5, 2, 3, 4, 1};
list.sort();

sort()方法默认按升序排序,如果需要降序排序可以使用qt的STL扩展排序函数:

QList<int> list = {5, 2, 3, 4, 1};
std::sort(list.begin(), list.end(), std::greater<int>());

3、过滤

QList提供了多种过滤方法来遍历列表,例如使用Qt的lambda表达式实现的过滤:

QList<int> list = {1, 2, 3, 4, 5};
QList<int> filtered = list.filter([](int i) { return i % 2 == 0; });
// filtered等于{2, 4},只包含偶数

4、Map和Reduce

QList提供了map()和reduce()方法来对列表中的元素进行转换和统计,例如:

QList<int> list = {1, 2, 3, 4, 5};
QList<int> mapped = list.map([](int i){ return i * 2; });
// mapped等于{2, 4, 6, 8, 10},每个元素都乘以2

QList<int> list = {1, 2, 3, 4, 5};
int sum = list.reduce([](int i, int j){ return i + j; });
// sum等于15,所有元素的和

四、使用实例

下面是一个使用QList实现学生成绩管理的例子。

1、定义学生和成绩数据类型

struct Student {
    QString name;
    int score;
};

QList<Student> studentList;

2、添加学生并按成绩排序

studentList.push_back({"John", 90});
studentList.push_back({"Mary", 80});
studentList.push_back({"Peter", 95});

// 按成绩排序
studentList.sort([](const Student &s1, const Student &s2) { return s1.score > s2.score; });

3、输出学生列表和平均分

// 遍历学生列表
QList<Student>::iterator it;
for (it = studentList.begin(); it != studentList.end(); ++it) {
    qDebug() << it->name << "score:" << it->score;
}

// 计算平均分
double sum = studentList.reduce(0, [](double i, const Student &s) { return i + s.score; });
double average = sum / studentList.size();
qDebug() << "average score:" << average;

Published by

风君子

独自遨游何稽首 揭天掀地慰生平