QList

QList 类是一个提供列表的模板类。它将项目存储在列表中,该列表提供基于索引的快速访问和基于索引的插入和删除。

要将项目插入列表,你可以使用 operator<<()insert()append()prepend()。例如:

operator<<()

QList<QString> list;
list << "one" << "two" << "three";

insert()

QList<QString> list;
list << "alpha" << "beta" << "delta";
list.insert(2, "gamma");

append()

QList<QString> list;
list.append("one");
list.append("two");
list.append("three");

prepend()

QList<QString> list;
list.prepend("one");
list.prepend("two");
list.prepend("three");

要访问特定索引位置的项目,你可以使用 operator[]()at()at() 可能比 operator[]() 更快,它永远不会导致容器的深层复制,应该在恒定时间内工作。他们都没有进行参数检查。例子:

if (list[0] == "mystring")
    cout << "mystring found" << endl;

要么

if (list.at(i) == "mystring")
    cout << "mystring found at position " << i << endl;

要删除项目,有 removeAt()takeAt()takeFirst()takeLast()removeFirst()removeLast()removeOne() 等功能。例子:

takeFirst()

// takeFirst() removes the first item in the list and returns it
QList<QWidget *> list;
...
while (!list.isEmpty())
    delete list.takeFirst();

removeOne()

// removeOne() removes the first occurrence of value in the list
QList<QString> list;
list << "sun" << "cloud" << "sun" << "rain";
list.removeOne("sun");

要查找列表中特定值的所有匹配项,可以使用 indexOf()lastIndexOf()。例:

indexOf()

int i = list.indexOf("mystring");
if (i != -1)
    cout << "First occurrence of mystring is at position " << i << endl;