QList和QSet常用操作(查找、插入、排序、交集)

1、QList常用操作(查找、插入、排序)
(1)QList查找(前提:已排序)
cpp 复制代码
/*[查找val在列表(已排序)中的位置,返回值范围[-1,0,,size()-1]]*/
int posOf(const QList<int> &list1, int val)
{
    auto it = std::find_if(list1.begin(), list1.end(), [val](int itemVal) {
        return (itemVal == val);
    });
    return ((it != list1.end()) ? (it - list1.begin()) : -1);
}

示例:list = 5,7,11,13,17,19

Pos of 3 is [-1], 11 is [2], 19 is [5], 23 is [-1].

(2)QList插入位置(前提:已排序)
cpp 复制代码
/*[获取val在列表(已排序)中的插入位置,返回值范围为[0,,size()]]*/
int insertPosOf(const QList<int> &list1, int val)
{
    auto it = std::lower_bound(list1.begin(), list1.end(), val, [](int itemVal, int val) {
        return itemVal < val;
    });
    return (it - list1.begin());
}

示例:list = 5,7,11,13,17,19

Insert pos of 3 is [0], 11 is [2], 19 is [5], 23 is [6].

(3) QList排序
  • 升序
cpp 复制代码
QList<int> list;
......
std::sort(list.begin(), list.end(), std::less<int>{});

cpp 复制代码
std::sort(list.begin(), list.end()); //默认为less<>{}

示例:list << 37 << 23 << 83 << 71 << 91 << 53 << 11 << 61 << 19;

list ASC = 11,19,23,37,53,61,71,83,91

  • 降序
cpp 复制代码
std::sort(list.begin(), list.end(), std::greater<int>{});

示例:list << 37 << 23 << 83 << 71 << 91 << 53 << 11 << 61 << 19;

list DESC = 91,83,71,61,53,37,23,19,11

2、QSet常用操作(交集)
cpp 复制代码
QList<int> listL;
QList<int> listR;
QList<int> list1;
......
{
    QSet<int> set1 = QSet(list1.constBegin(), list1.constEnd());
    QSet<int> setL = QSet(listL.cbegin(), listL.cend());
    set1.intersect(setL);
    QList<int> list1L = QList(set1.cbegin(), set1.cend());
    std::sort(list1L.begin(), list1L.end());
}

示例:

listL << 0 << 2 << 4 << 6 << 8 << 10 << 12 << 14 << 16 << 18 << 20 << 22;

listR << 1 << 3 << 5 << 7 << 9 << 11 << 13 << 15 << 17 << 19 << 21 << 23;

list1 << 3 << 6 << 8 << 11 << 14 << 15 << 18 << 21;

list1L(list1 intersect listL) = 6, 8,14,18

list1R(list1 intersect listR) = 3,11,15,21

相关推荐
Ryan_Gosling18 分钟前
C++-构造函数-接口
开发语言·c++
ceffans28 分钟前
PDF文档中文本解析
c++·windows·pdf
SummerGao.34 分钟前
Windows 快速搭建C++开发环境,安装C++、CMake、QT、Visual Studio、Setup Factory
c++·windows·qt·cmake·visual studio·setup factory
仟濹38 分钟前
【二分搜索 C/C++】洛谷 P1873 EKO / 砍树
c语言·c++·算法
YH_DevJourney1 小时前
Linux-C/C++《C/8、系统信息与系统资源》
linux·c语言·c++
Igallta_8136222 小时前
【小游戏】C++控制台版本俄罗斯轮盘赌
c语言·开发语言·c++·windows·游戏·游戏程序
在雨中6123 小时前
【找工作】C++和算法复习(自用)
c++·算法
攻城狮7号4 小时前
【第二节】C++设计模式(创建型模式)-抽象工厂模式
c++·设计模式·抽象工厂模式
天线枫枫4 小时前
QT- HTTP + JSON(还需完善)
c++·qt·http
天若有情6735 小时前
【数据结构】C++实现链表数据结构
数据结构·c++·链表