QSet是Qt中的一个容器,用于储存一组唯一的元素。它提供了高效的插入、查找、删除操作,并且之确保每个元素只出现一次。
#include<QSet>
QSet<int> mySet;
mySet = {1,2,3};
QSet<int> otherSet = {4,5,6};
QSet<int> mySet = otherSet; //从另一个QSet复制构造
1、插入元素:可以使用insert()函数进行插入
mySet.insert(4);//插入单个数据
QSet<int> otherSet = {5,6,7};
mySet.insert(otherSet.begin(),otherSet.end());//插入一组数据
2、查找元素:可以使用contains()函数,判断元素是否在QSet中
if(mySet.contains(3))
{
//元素存在
}
else
{
//元素不存在
}
3、删除元素:可以使用remove()函数
mySet.remove(2);//删除单个元素
QSet<int> otherSet = {4,5,6};
mySet.subtract(otherSet);//删除一组数据
4、遍历元素:可以使用迭代器或者foreach
for(auto it = mySet.begin();it != mySet.end();++it){
int element = *it;
//处理元素
}
for(int elemnet:mySet){
//处理元素
}
QSet还提供了其他函数,如size()获取元素个数,isEmpty()检查是否为空,unite()合并两个QSet等。
QSet中的元素是无序的,QSet中的存储元素不会按照插入顺序进行排序。