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;