QVector
儲存一系列給定的值,在頭部或中間插入值會變得緩慢。
#include
...

QVector vals = {1, 2, 3, 4, 5};

out << vals.size() << endl; // 5

out << vals.first() << endl; // 1
out << vals.last() << endl; // 5

vals.append(6); //從後方加入 6
vals.prepend(0); // 從前方加入 0

//0 1 2 3 4 5 6
for (int val : vals) {
out << val << " ";
}


QList
最常用通用的containers。
QList authors = {"Balzac", "Tolstoy", "Gulbranssen", "London"};

for (int i=0; i < authors.size(); ++i) {
out << authors.at(i) << endl;
}

/*
Balzac
Tolstoy
Gulbranssen
London
*/

authors << "Galsworthy" << "Sienkiewicz"; //insert "Galsworthy","Sienkiewicz"

std::sort(authors.begin(), authors.end());//asc 升冪排序

for (QString author : authors) {
out << author << endl;
}
/*
Balzac
Galsworthy
Gulbranssen
London
Sienkiewicz
Tolstoy
*/


QStringList
繼承自QList
QString string = "coin, book, cup, pencil, clock, bookmark";
QStringList items = string.split(",");
items << "alpha" << "beta" << "gamma" << "epsilon";
QStringListIterator it(items); //建立 Iterator

while (it.hasNext()) {
out << it.next().trimmed() << endl;
}

/*
coin
book
cup
pencil
clock
bookmark
alpha
beta
gamma
epsilon
*/

QSet
提供單值的數學上面的集合,具有快速的查找性能
QSet cols1 = {"yellow", "red", "blue"};
QSet cols2 = {"blue", "pink", "orange"};

cols1.insert("brown");

cols1.unite(cols2); // 像js concat(),聯集兩個QSet

out << cols1.size() << endl; // 6

//QSet不支援sort
//宣告一個QList ,利用values()回傳建立一個QList型態物件
QList lcols = cols1.values();
std::sort(lcols.begin(), lcols.end());


QMap
QMap所存儲的數據類型是一個鍵對應一個值,並以key的次序順序存儲數據。
如果顺序無關,QHash提供了更好的性能,QHash是以任意的順序住址存儲數據。
QMap items = { {"coins", 5}, {"books", 3} };

items.insert("bottles", 7);

QList values = items.values();

for (int val : values) {
out << val << endl; //列出值
}

/*
3
7
5
*/

QList keys = items.keys();

out << "Keys:" << endl;
for (QString key : keys) {
out << key << endl; //列出key
}

/*
books
bottles
coins
*/

QMapIterator it(items);

while (it.hasNext()) {
it.next();
out << it.key() << ": " << it.value() << endl;//列出key與val
}

/*
books: 3
bottles: 7
coins: 5
*/

QMap::iterator mi;

mi = items.find("books"); //找到key

if(mi != items.end()) {
mi.value() = 10; //更改值
}

QMap::const_iterator i;

for( i=items.constBegin(); i!=items.constEnd(); ++i) {
out << i.key() <<" " << i.value() << endl;
}

/*
books: 10
bottles: 7
coins: 5
*/


參考: