其他分享
首页 > 其他分享> > Qt的容器类

Qt的容器类

作者:互联网

1. 注意点:

1)基于模板的容器类;

2)存储在容器中的数据必须是可赋值的数据类型。

  即必须提供默认构造函数,拷贝构造函数和赋值操作。

 

2. 常见容器类:
1)QList<T>:维护了一个指针数组,可基于下标快速访问,对不同类型的数据会采取不同的存储策略;

  继承自 QList 的子类有 QItemSelection,QQueue,QSignalSpy,QStringList 和 QTestEventList 。

2)QLinkedList<T>:链式列表,不能下标,只能迭代; 

  继承自 QLinkedList 的子类有 QPolygon,QPolygonF 和 QStack 。

3)QVector<T>:连续存储,既能下标,也能迭代。

 

3. 如何遍历容器类?

1)JAVA风格的迭代器:迭代点位于表前,表后,或两项之间。

  只读:QListIterator<T>;读写:QMutableListIterator<T>

  ......

  ep:

 1 #include <QDebug>
 2 
 3 int main(int argc, char *argv[])
 4 {
 5     QList <int> list;
 6     QMutableListIterator <int> it(list);
 7 
 8     for (int i = 0; i < 10; i++) {
 9         it.insert(i);
10     }
11 
12     for (it.toFront(); it.hasNext();)
13         qDebug()<<it.next();
14 
15     qDebug()<<'\n';
16 
17     for (it.toBack(); it.hasPrevious();) {
18         if (0 == it.previous() % 2)
19             it.remove();
20         else
21             it.setValue(it.peekNext() * 10);
22     }
23 
24     for (it.toFront(); it.hasNext();)
25         qDebug()<<it.next();
26 }

 

2)STL风格的迭代器:迭代点直接指向列表项,API 基于指针,可 ++ 或 * 操作。

  只读:QList<T>::connst_iterator;读写:QList<T>::iterator。

  ......

  ep:

 1 #include <QDebug>
 2 
 3 int main(int argc, char *argv[])
 4 {
 5     QList <int> list;
 6     for (int i = 0; i < 10; i++)
 7         list<<i;
 8 
 9     QList<int>::iterator it;
10     for (it = list.begin(); it != list.end(); ++it) {
11         qDebug()<<(*it);
12         *it *= 10;
13     }
14 
15     qDebug()<<'\n';
16 
17     QList<int>::const_iterator cit;
18     for (cit = list.begin(); cit != list.end(); ++cit) {
19         qDebug()<<(*cit);
20     }
21 }

 

4. QMap 和 QHash

 

标签:容器,Qt,迭代,int,list,++,iterator,QList
来源: https://www.cnblogs.com/XieJX/p/15937642.html