Qt container and common algorithms

container

The use of these containers is the same as the basic structure of stl learning

As long as it is data, a container must be used, and the data in the program is placed in the container for easy addition, deletion, modification and query.

 

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↓↓  

The Qt library provides a set of generic template-based container classes (container classes). These container classes can be used to store specified types of items (items), for example, if you need a variable-sized array of type QString, you can use QVector(QString). Compared with container classes in STL (Standard Template Library, C++'s standard template library), these container classes in Qt are lighter, safer, and easier to use

There are many traversal methods, mainly using STL style for traversal

STL-style iterators are compatible with Qt and STL's generic algorithms, and are optimized for speed. For each container class, there are two STL-style iterator types: one provides read-only access, and the other provides read-write access. Because read-only iterators are much faster than read-write iterators, read-only iterators should be used whenever possible.

The API of the STL-style iterator mimics the pointer of the array, for example, use the "++" operator to move the iterator backward to point to the next item; use the "*" operator to return the item pointed to by the iterator, etc. STL-style iterators point directly to items. The begin() function of one of the containers returns an iterator pointing to the first item in the container, and the end() function also returns an iterator, but this iterator points to the imaginary virtual space next to the last item in the container. item, end() marks an invalid position, and the begin() function is equivalent to the end() function when the list is empty.

1、QList

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

QList provides many convenient interface functions to manipulate items in the list, for example:

Insert operation insert(); replace operation replace(); remove operation removeAt(); move operation move(); exchange operation swap(); add item append() at the end of the table; add item prepend() at the head of the table; Remove the first item removeFirst(); remove the last item removeLast(); remove an item from the list and get the item takeAt(), and corresponding takeFirst() and takeLast(); get the index of an item indexOf(); Determine whether it contains the corresponding item contains(); Obtain count() of the number of occurrences of an item.

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

QList<QString> strList;
strList<<"AA"<<"BB"<<"CC"<<"DD";//放入4个字符串
QList<QString>::iterator i;//读写迭代器
for(i=strList.begin();i!=strList.end();i++)
{
	*i=i->toLower();//转小写
	qDebug()<<*i;//输出为小写的aa bb cc dd
}

while(i!=strList.begin())
{
	i--;
	qDebug()<<*i;//输出 dd cc bb aa
}

while(i!=strList.begin())
{
	i--;
	qDebug()<<*i;//输出 dd cc bb aa
}


//遍历方式
//1、for循环遍历
for(int i=0;i<strList.size();i++)
{
	qDebug()<<strList[i];
}
//2、foreach
foreach(QString itm,strList)
{
	qDebug()<<itm;
}
//3、只读迭代器
QListIterator<QString> it1(strList);
while(it1.hasNext())
{
	qDebug()<<it1.next();
}
//4、迭代器方式遍历
for(i=strList.begin();i!=strList.end();i++)
{
	*i=i->toLower();//转小写
	qDebug()<<*i;//输出为小写的aa bb cc dd
}



2、QLinkedList

List based on iterator access, convenient and fast insertion and deletion

QLinkedList<int> list;
list<<1<<2<<3<<4<<5;
foreach(int i,list)
{
   qDebug()<<i;//1 2 3 4 5
}

3、QVectot

initialization:

QVector<int> v1(5); //开辟5个大小的空间
QVector<int> v2(5,1); //5个值,都是1
QVector<int> v3(v1); //用另一个QVector初始化

Increase:

QVector<int> v;
push_back(5); //在数组后添加元素
push_front(4); //在数组首位置添加元素
prepend(3); //在数组首位置添加元素
append(6); //在数组最后添加元素
v << 7; //在数组最后添加元素,相当于尾插
insert(0,2); //在数组位置0,添加元素
insert(0,2,1); //在数组位置0,添加2个值为1的元素
insert(myVector.end(),8); //在数组最后,添加一个82
insert(myVector.end(),2,9); //在数组最后,添加2个值为9的元素

delete:

remove(0,2); //从位置0开始,移除2个元素
remove(0); //移除位置0的元素
pop_back(); //移除最后一个元素
pop_front(); //移除第一个元素
clear(); //清除所有元素
erase(myVector.begin());//移除某位置的元素
erase(myVector.begin(),myVector.end());//移除区间所有元素

change:

replace(0,10);//位置0上的元素,用10来代替

Find:

indexOf(2,0);//从位置0开始,查找元素2,返回下标
myVector.lastIndexOf(2,1);//从右向左数,位置0开始查找元素2,返回下标
myVector.startsWith(2);//判断,第一个元素是否是2
myVector.endsWith(2);//判断,最后一个元素是否是2

Convert:

//将QVector转为std::Vector
std::vector<int> stdVector = myVector.toStdVector();

//将QVector转为QList
QList<int> list = myVector.toList();
qDebug() << list;

//将std::Vector转为QVector
myVector.clear();
myVector = QVector<int>::fromStdVector(stdVector);
qDebug() << myVector;

//将QList转为QVector
myVector.clear();
myVector = QVector<int>::fromList(list);
qDebug() << myVector;

Some examples:

QVector<int> v;
v<<1<<2<<3<<66<<4<<5<<6;
v.insert(2,99);//在下标为2的位子插入一个99
qDebug()<<v;//全部输出
qDebug()<<v.indexOf(66,0);//从0开始查找66,返回下标

4、QMap

The QMap class is a container class that provides a skip list based dictionary. QMap is one of Qt's general-purpose 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:

Insert operation insert();

Get value value();

Whether to contain a key contains();

delete a key remove();

Delete a key and get the value corresponding to the key take();

Empty operation clear();

Insert one-key multi-value insertMulti().

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. To avoid this situation, You can use the value() function to get the value of a 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.

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

map.insert("seven",7); // 使用insert()函数进行插入
// 获取键的值,使用“[ ]”操作符时,如果map中没有该键,那么会自动插入
int value1 = map["six"];
qDebug() << "value1:" << value1;
qDebug() << "contains 'six' ?" << map.contains("six");

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

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

QList<int>::const_iterator itm;
QMap<int,QString> Employees;
Employees.insert(1,"Bob");
Employees.insert(2,"Chad");
Employees.insert(3,"Mary");
Employees.insert(4,"oldWang");
Employees[5] = "rebote"; //不推荐这样赋值
QMap<int, QString>::const_iterator i = Employees.constBegin();
while (i != Employees.constEnd())
{
	std::cout << i.key() << ": " << i.value().toStdString()<<std::endl;
	++i;
}

QMap<int, QString>::iterator ii = Employees.begin();
while (ii != Employees.end()) 
{
	if(ii.value() == "oldWang")
	{
		ii.value() = "robort";
	}
	++i;
}

5、QHash

The difference between QMap and QHash:

QHash has a faster lookup speed than QMap

QHash stores data items in any order, while QMap always stores data in key order

The key type Key of QHash must provide operator==() and a global qHash(Key) function, while the key type Key of QMap must provide the operator<() function.

QHash<int,QString> Employees;
Employees.insert(2,"Bob");
Employees.insert(1,"Chad");
Employees.insert(3,"Mary");
foreach(int i, Employees.keys())
{
	qDebug() << Employees[i];
}

QHashIterator<int,QString> Iter(Employees);
while(Iter.hasNext())
{
	Iter.next();
	qDebug() << Iter.key() << " = " << Iter.value();
}

common algorithm

In the header file, Qt provides some global template functions, which are very commonly used algorithms that can be used on containers. We can use these algorithms on any container class that provides STL-style iterators, including QList, QLinkedList, QVector, QMap, and QHash.

1、qsort

bool fun(int a,int b)
{
	return a>b;
}
//类似stl中sort用法

QList<int> list;
list << 36 << 16 << 66 << 6 << 56;
qSort(list.begin(), list.end());//小到大
qDebug()<<list;
qSort(list.begin(), list.end(),fun);//大到小,多一个参数,比较方式
qDebug()<<list;

2、qcopy

QStringList list;
list << "a" << "b" << "c";

QVector<QString> vect(3);
//第一个参数:拷贝起始点,第二个参数:拷贝终止点,第三个参数:拷贝到哪里
qCopy(list.begin(), list.end(), vect.begin());
foreach (QString item, vect)
{
	qDebug() << item;
}

3、qFind

QList<QString> list;
list<<"qwq"<<"ewrw"<<"e";

//在list中查找"e"是否存在
//第一个参数:查找起始点,第二个参数:查找终止点,第三个参数:查找什么值
QList<QString>::const_iterator iter=qFind(list.begin(),list.end(),"e");
if(iter!=list.end())
{
	qDebug()<<*iter;
}
else
{
	qDebug()<<"not fond";
}

The article is transferred from Blog Garden (Xuan Zhe): qt container and commonly used algorithms - Xuan Zhe - Blog Park

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/132119453