C/C++ std::list 插入时即整理顺序(ASC升序)

下面是一个随机的 packet(帧)插入函数,ASC升序,按 "packet_seq" 来控制成员之间的顺序,该函数优化了,倾向头、倾向尾。

即:

根据 packet_seq 可以得出,插入位置的最短距离,更偏向左侧、还是右侧,该函数实现仅供参考,若需要多线程访问,需要确保 "代码临界区同步问题"。

cpp 复制代码
#include <iostream>
#include <list>
#include <memory>

struct tag_packet {
    uint32_t packet_seq;
};

void emplace_packet(std::list<tag_packet>& queue, const tag_packet& packet) {
    for (;;) {
        auto tail = queue.begin();
        if (tail == queue.end()) {
            queue.emplace_back(packet);
            break;
        }

        if (tail->packet_seq > packet.packet_seq) {
            queue.emplace_front(packet);
            break;
        }

        auto rtail = queue.rbegin();
        if (rtail->packet_seq <= packet.packet_seq) {
            queue.emplace_back(packet);
            break;
        }

        if ((packet.packet_seq - tail->packet_seq) > (rtail->packet_seq - packet.packet_seq)) {
            auto position = std::upper_bound(queue.rbegin(), queue.rend(), packet,
                [](const tag_packet& lhs, const tag_packet& rhs) noexcept {
                    return lhs.packet_seq > rhs.packet_seq;
                });

            queue.emplace(position.base(), packet);
        }
        else {
            auto position = std::lower_bound(queue.begin(), queue.end(), packet,
                [](const tag_packet& lhs, const tag_packet& rhs) noexcept {
                    return lhs.packet_seq < rhs.packet_seq;
                });

            queue.emplace(position, packet);
        }

        break;
    }
}

int main() {
    std::list<tag_packet> packets;
    tag_packet packet1 = { 100  };
    tag_packet packet2 = { 50, };
    tag_packet packet3 = { 200  };
    tag_packet packet4 = { 150  };
    tag_packet packet5 = { 75 };
    tag_packet packet6 = { 115 };
    tag_packet packet7 = { 45 };
    tag_packet packet8 = { 135 };
    tag_packet packet9 = { 195 };

    emplace_packet(packets, packet1);
    emplace_packet(packets, packet2);
    emplace_packet(packets, packet3);
    emplace_packet(packets, packet4);
    emplace_packet(packets, packet5);
    emplace_packet(packets, packet6);
    emplace_packet(packets, packet7);
    emplace_packet(packets, packet8);
    emplace_packet(packets, packet9);

    for (const auto& packet : packets) {
        std::cout << packet.packet_seq << std::endl;
    }

    return 0;
}
相关推荐
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境3 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境3 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴4 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境6 天前
C++ 的Eigen 库全解析
c++
卷无止境6 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴6 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18008 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴8 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake