Qt container class: Introduction to Qt container class

1. Introduction

The Qt library provides a set of generic template-based container classes that can be used to store items of specified types. For example, if you need an array of variable-sized QStrings, use QVector<QString>.

These container classes are designed to be lighter, safer, and easier to use than STL (C++ Standard Template Library) containers. If you are not familiar with the STL, or prefer to use the "Qt way", then you can use these classes instead of using the STL classes.

You can iterate over items stored in a container in two ways: Java-style iterators and STL-style iterators. Java-style iterators are easier to use and provide more advanced features; STL-style iterators are more efficient and can be used with Qt and STL generic algorithms.

Qt also provides the foreach keyword to allow us to easily traverse the items in the container.

2. Containers

Qt provides some sequential containers: QList, QLinkedList, QVector, QStack and QQueue. Because the data in these containers are stored linearly one after the other, they are called sequential containers. Most of the time, QList is the best choice. Although it is implemented with an array, it is very fast to add elements at the beginning and end of it. Use QLinkedList if you need a linked-list; use QVector if you want your items to be stored contiguously in memory. QStack and QQueue (stack and queue) respectively provide last-in-first-out (LIFO) and first-in-first-out (FIFO) mechanisms.

Qt also provides some associative containers: QMap, QMultiMap, QHash, QMultiHash, QSet. Because these containers store <key, value> pairs, such as QMap<Key, T>, they are called associative containers. Among them, the "Multi" container supports one key corresponding to multiple values. The "Hash" container uses the hash function for fast lookups on sorted sets, without binary search.

The following table introduces the commonly used container classes.

kind

overview

QList<T>

This is currently the most frequently used container class, which stores a string of values ​​of a specified type (T), which can be obtained by indexing. Essentially QList is implemented with an array, which ensures very fast index-based access.

QLinkedList<T>

Similar to QList, but it uses iterators instead of integer indices to get items. It provides better performance when inserting items in the middle of a large list, and it has a better iterator mechanism.

QVector<T>

Storing a set of values ​​in contiguous locations in memory, inserting at the beginning or in the middle is very slow because it causes many items in memory to be shifted by one location.

QStack<T>

A subclass of QVector that provides a last-in, first-out mechanism. Several methods have been added to the current QVector: push(), pos(), top().

QQueue<T>

A subclass of QList, which provides a first-in first-out mechanism, adds several methods to the current QList: enqueue(), dequeue(), head().

QSet<T>

A mathematical collection of single values ​​that can be looked up quickly.

QMap<Key, T>

A dictionary (associative array) is provided that maps keys of type Key to values ​​of type T. Usually a key corresponds to a value, QMap stores data in the order of Keys, if the order is not important, QHash is a faster choice.

QMultiMap<Key, T>

A subclass of QMap that provides a multi-value interface, one key corresponds to multiple values.

QHash<Key, T>

Has almost the same interface as QMap, but is faster to lookup. QHash stores data in no order.

QMultiHash<Key, T>

A subclass of QHash that provides a multi-value interface.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Containers can also be nested, such as QMap<QString, QList<int> >, where the key type is QString, and the value type is QList<int>. It should be noted that there must be A space, otherwise the compiler will treat it as the ">>" operator.

The value type stored in various containers can be any assignable data type, such as basic type double, pointer type, Qt data type (such as QString, QDate, QTime), etc. However, QObject and subclasses of QObject cannot be stored in containers, but pointers to these classes can be stored, such as QList<QWidget *>.

3. Sample programs of QList and QMap

The following introduces the most commonly used QList and QMap, and for other containers, you can refer to them, because their interface functions are very similar, of course, you can also refer to the help manual.

Sample program for QList

Create a new Qt
5 console application, and the project name is
myQList. This is just to demonstrate the use of the QList container class, so no graphical interface is used, so you only need to create a console program. Change the main.cpp file as follows:

#include <QCoreApplication>
#include <QList>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //创建QList列表
    QList<QString> list;

    //插入项目
    list << "aa" << "bb";

    //在列表尾部添加
    list.append("cc");
    //在列表头部添加
    list.prepend("mm");

    //将第一个项目值换为“bc”
    list.replace(0, "ss");

    //第一次遍历输出列表项目值
    qDebug() << "the no.1 list is: ";
    for(int i=0; i<list.size(); ++i)
    {
        qDebug() << list.at(i);   //现在列表为ss aa bb cc
    }
    qDebug() << endl;

    //----------------------------------------------------------
    QString str = list.takeAt(1); //从列表中删除位置1的项目,并获取它
    qDebug() << "at(1) item is: " << str;

    //在位置1插入项目
    list.insert(1, "ab");
    //交换项目1和项目2
    list.swap(1,2);

    //第二次遍历输出列表项目值
    qDebug() << "the no.2 list is: ";
    for(int i=0; i<list.size(); ++i)
    {
        qDebug() << list.at(i);   //现在列表为ss bb ab cc
    }
    qDebug() << endl;

    //-----------------------------------------------------------
    //查询列表中是否包含“ss”
    qDebug() << "contains 'ss' ?" << list.contains("ss");
    //查询列表中包含“mm”的个数
    qDebug() << "the 'ss' count: " << list.count("ss");
    // 第一个“ss”的位置,默认从位置0开始往前查找,返回第一个匹配的项目的位置
    qDebug() << "the first 'ss' index: " << list.indexOf("ss");
    // 第二个“ss”的位置,我们指定从位置1开始往前查找,未找到则返回-1
    qDebug() << "the second 'ss' index: " << list.indexOf("ss", 1);

    return a.exec();
}

Run the program, Qt's "Application Output" window output is as follows:

the no.1 list is:
"ss"
"aa"
"bb"
"cc"

at(1) item is:  "aa"
the no.2 list is:
"ss"
"bb"
"ab"
"cc"

contains 'ss' ? true
the 'ss' count:  1
the first 'ss' index:  0
the second 'ss' index:  -1

QList is a template class that provides a list. QList<T> is actually an array of pointers to T-type items, so it supports index-based access, and when the number of items is less than 1000, it can implement fast insertion in the middle of the list.

QList provides many convenient interface functions to operate the items in the list, such as insertion operation insert(), replacement operation replace(), removal operation removeAt(), movement operation move(), exchange operation swap(), at the end of the table Add item append(), add item prepend() in the header, remove an item from the list and get the item takeAt() and the corresponding takeFirst() and takeLast(), get the index indexOf() of an item, judge Whether it contains the corresponding item contains() and get count() of the number of occurrences of an item, etc.

For QList, you can use the "<<'' operator to insert items into the list, or you can use the "[]" operator to access an item through an index, where items are numbered from 0. However, for read-only Access, another way is to use the at() function, which is much faster than the operator.

Sample program for QMap

Create a new Qt
5 console application with the project name
myMap. This is just to demonstrate the use of the QMap container class, so no graphical interface is used, so you only need to create a console program. Change the main.cpp file as follows:

#include <QCoreApplication>
#include <QMap>
#include <QMultiMap>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //创建QMap
    QMap<QString, int> map;
    map["one"] = 1;          //向map中插入("one",1)
    map["three"] = 3;

    //使用insert()函数进行插入
    map.insert("seven", 7);

    //获取键的值,使用“[ ]”操作符时如果map中没有该键,那么会自动插入
    int value1 = map["six"]; //如果map中没有该键,则返回0
    qDebug() << "value1:" << value1;
    qDebug() << "contains 'six' ?" << map.contains("six") << endl;

    //使用value()函数获取键的值,这样当键不存在时不会自动插入
    int value2 = map.value("five");
    qDebug() << "value2:" << value2;
    qDebug() << "contains 'five' ?" << map.contains("five") << endl;

    //当键不存在时,value()默认返回0,这里可以设定该值,比如这里设置为9
    int value3 = map.value("nine", 9);
    qDebug() << "value3:" << value3 << endl;

    //map默认是一个键对应一个值,如果重新给该键设置了值,那么以前的会被擦除
    map.insert("ten", 10);
    map.insert("ten", 100);
    qDebug() << "ten: " << map.value("ten") << endl;

    //可以使用insertMulti()函数来实现一键多值,然后使用values()函数来获取值的列表
    map.insertMulti("two", 2);
    map.insertMulti("two", 4);
    QList<int> values = map.values("two");
    qDebug() << "two: " << values << endl;

    //------------------------------------------------------------------

    //也可以使用QMultiMap类来实现一键多值
    QMultiMap<QString, int> map1, map2, map3;
    map1.insert("values", 1);
    map1.insert("values", 2);
    map2.insert("values", 3);
    //可以进行相加,这样map3的“values”键将包含2,1,3三个值
    map3 = map2 + map1;
    QList<int> myValues = map3.values("values");
    qDebug() << "the values are: ";
    for (int i=0; i<myValues.size(); ++i)
    {
        qDebug() << myValues.at(i);
    }

    return a.exec();
}

Run the program, Qt's "Application Output" window output is as follows:

value1: 0
contains 'six' ? true

value2: 0
contains 'five' ? false

value3: 9

ten:  100

two:  (4, 2)

the values are:
2
1
3

The QMap class is a container class that provides a skip-list-based dictionary. QMap<Key,T> is one of Qt's generic container classes, which store (key, value) pairs and provide fast lookup of the value associated with the key.

QMap provides many convenient interface functions, such as insertion operation inSert(), get value value(), whether to include a key contains(), delete a key remove(), delete a key and get the value corresponding to the key take (), insert one-key multi-value insertMulti(), etc.

You can use the "[]" operator to insert a key-value pair or get the value of a key, but when using this operator to get the value of a key that does not exist, the key will be inserted into the map by default; in order to avoid this situation , you can use the value() function to get the value of the key. When using the value() function, if the specified key does not exist, it will return 0 by default. You can provide parameters when using this function to change the value returned by default. QMap defaults to one key corresponding to one value, but you can also use insertMulti() to insert one key and multiple values. For the case of one key and multiple values, it is more convenient to use QMultiMap, a subclass of QMap.

The article is transferred from the blog garden (fengMisaka): One of the Qt container classes: Introduction to Qt container classes - fengMisaka - 博客园

The benefits of this article, free to receive Qt development learning materials package, technical video, including (C++ language foundation, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/QtCompany/article/details/131794991