在Qt中,QList 是一个动态数组容器类,用于存储和管理相同类型的元素。它提供了快速随机访问、动态扩展和丰富的操作方法,是Qt中最常用的容器类之一。
list[0]
)。性能考虑:
如果需要频繁在中间插入/删除元素,可考虑使用 QLinkedList
;如果需要键值对存储,可使用 QMap
或 QHash
。
#include
#include
// 创建空列表
QList<int> intList;
QList<QString> stringList;
// 使用初始化列表创建
QList<int> numbers = {1, 2, 3, 4, 5};
QList<QString> names = {"Alice", "Bob", "Charlie"};
// 从现有列表复制
QList<int> copyList(numbers); // 深拷贝
// 指定初始大小和值
QList<QString> emptyNames(5, ""); // 创建包含5个空字符串的列表
// 添加元素
QList<QString> list;
list.append("Apple"); // 在末尾添加
list.prepend("Banana"); // 在开头添加
list.insert(1, "Cherry"); // 在索引1处插入
// 删除元素
list.removeAt(1); // 删除索引1的元素
list.removeFirst(); // 删除第一个元素
list.removeLast(); // 删除最后一个元素
list.removeOne("Apple"); // 删除第一个匹配的元素
list.removeAll("Apple"); // 删除所有匹配的元素
// 清空列表
list.clear();
// 通过索引访问(不检查边界)
QString first = list[0]; // 读取
list[0] = "New Value"; // 修改
// 通过at()访问(检查边界,越界时抛出异常)
QString second = list.at(1);
// 获取列表大小
int size = list.size(); // 或 list.count()
// 判断列表是否为空
bool isEmpty = list.isEmpty(); // 或 list.size() == 0
// 获取第一个和最后一个元素
QString firstItem = list.first(); // 或 list.front()
QString lastItem = list.last(); // 或 list.back()
// 查找元素位置(返回第一个匹配的索引,未找到返回-1)
int index = list.indexOf("Apple");
int lastIndex = list.lastIndexOf("Apple");
// 判断是否包含元素
bool containsApple = list.contains("Apple");
// 统计元素出现次数
int count = list.count("Apple");
基于索引的遍历
for (int i = 0; i < list.size(); ++i) {
qDebug() << list[i];
}
基于迭代器的遍历
// 只读迭代器
QList<QString>::const_iterator it;
for (it = list.constBegin(); it != list.constEnd(); ++it) {
qDebug() << *it;
}
// 读写迭代器
QList<QString>::iterator mutableIt;
for (mutableIt = list.begin(); mutableIt != list.end(); ++mutableIt) {
*mutableIt = "Modified";
}
C++11范围for循环
for (const QString &item : list) {
qDebug() << item;
}
// 可修改的版本
for (QString &item : list) {
item = "Modified";
}
// 排序(升序)
QList<int> numbers = {3, 1, 4, 2};
std::sort(numbers.begin(), numbers.end()); // 标准库排序
// 自定义排序(降序)
std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
return a > b;
});
// 筛选元素(使用STL算法)
QList<int> evenNumbers;
std::copy_if(numbers.begin(), numbers.end(),
std::back_inserter(evenNumbers),
[](int num) { return num % 2 == 0; });
// QList 转 QVector
QVector<int> vector = numbers.toVector();
// QList 转 std::list
std::list<int> stdList = numbers.toStdList();
// std::vector 转 QList
std::vector<double> stdVector = {1.1, 2.2, 3.3};
QList<double> qList = QList<double>::fromStdVector(stdVector);
#include
#include
void listExample() {
// 创建列表并添加元素
QList<QString> fruits;
fruits.append("Apple");
fruits.append("Banana");
fruits.prepend("Cherry");
// 遍历列表
qDebug() << "所有水果:";
for (const QString &fruit : fruits) {
qDebug() << fruit;
}
// 修改元素
if (fruits.size() > 1) {
fruits[1] = "Blueberry";
}
// 查找元素
int index = fruits.indexOf("Apple");
if (index != -1) {
qDebug() << "找到Apple,索引为:" << index;
}
// 删除元素
fruits.removeOne("Cherry");
// 排序
fruits.sort();
// 输出排序后的列表
qDebug() << "排序后的水果:";
for (const QString &fruit : fruits) {
qDebug() << fruit;
}
}