qt容器类的使用
程序员文章站
2022-06-17 07:54:30
...
添加头文件
#include<QtDebug>
#include<QList>
#include<QVector>
#include<QHash>
#include<QStack>
#include<QQueue>
#include<QMap>
相应容器类的关键用法代码
//队列
QQueue<int> myqueue;
myqueue.enqueue(10);
myqueue.enqueue(20);
myqueue.enqueue(60);
while (!myqueue.isEmpty()) {
qDebug() << myqueue.dequeue() <<endl;
}
QQueue<string> queue;
queue.enqueue("hello");
queue.enqueue("world");
queue.enqueue("qt code");
while (!queue.isEmpty()) {
qDebug() <<"QQueue: "<< queue.dequeue().data() <<endl;
// printf("%s \n",queue.dequeue().data());
}
//栈
QStack<int> mystack;
mystack.push(10);
mystack.push(20);
mystack.push(30);
while (!mystack.isEmpty()) {
qDebug()<<"QStack: "<< mystack.pop() <<endl;
}
QVector<int> myvector;
myvector.append(50);
myvector.append(30);
myvector.append(20);
myvector.push_front(100);
QVector<int>::iterator iter;
for (iter=myvector.begin();iter != myvector.end();iter++) {
qDebug() <<"QVector: "<< *iter << endl;
}
QList<string> mylist;
mylist.append("hello ");
mylist.append("world ");
mylist.push_front("list : ");
QList<string>::iterator list_iter;
for (list_iter=mylist.begin();list_iter != mylist.end();list_iter++) {
qDebug()<<"QList: "<< list_iter->data() <<endl;
}
qDebug()<<"test2: " <<endl;
mylist.insert(2,"2 world");
mylist.replace(0,"123456");
for (list_iter=mylist.begin();list_iter != mylist.end();list_iter++) {
qDebug()<<"QList: "<< list_iter->data() <<endl;
}
//hash与map类似
//hash
QHash<QString ,int> myhash;
myhash.insert("alen",1);
myhash["lucy"]=2;
myhash["peter"]=3;
QHashIterator<QString ,int> hash_iter(myhash);
while (hash_iter.hasNext()) {
hash_iter.next();
qDebug() << hash_iter.key() << ":" << hash_iter.value();
}
//map
QMap<QString, int> map;
map.insert("key 2", 2);
map.insert("key 0", 0);
map.insert("key 1", 1);
map["key 3"]=3;
// 通过QList获取键值对
QList<QString> kList = map.keys();
for(int i=0; i<kList.count(); i++)
{
qDebug() << kList[i];
}
QList<int> vList = map.values();
for(int i=0; i<vList.count(); i++)
{
qDebug() << vList[i];
}
// 通过QMapIterator获取键值对
QMapIterator<QString, int> it(map);
while(it.hasNext())
{
it.next();
qDebug() << it.key() << ":" << it.value();
}