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;
}
相关推荐
FlightYe2 小时前
视界原理之3D视频(四):裸眼、眼镜和头显
android·linux·c++·3d·ffmpeg·音视频
蹊黎3 小时前
Linux 下用 C 语言实现进度条
linux·c语言·单片机
by209993 小时前
C++ 智能指针的所有权与使用
开发语言·c++·经验分享
视觉小萌新3 小时前
AI Class 3 · Chapter 1:变量、字符串、list/dict、if/for(python学习-小白版-有经验可跳过)
python·学习·list
Rover Ramble3 小时前
C++ 用互斥锁实现读写锁
开发语言·c++
你怎么知道我是队长4 小时前
C++零基础入门第2周:数据类型、运算符与表达式完全指南(附20段可运行代码+避坑清单)
c++
say_fall4 小时前
【Linux系统编程】Ext 文件系统:磁盘与存储、文件与目录、现代计算机究竟如何寻找文件
linux·运维·服务器·数据库·c++
雪落漂泊5 小时前
C++算法 滑动窗口篇(下)
开发语言·c++
爱聊灵光的维C5 小时前
从看见世界到重构认知:在视觉与硬件的交汇处,寻找我们这代人的北极星
c语言·物联网·计算机视觉·重构·硬件工程·射频工程
AI+程序员在路上5 小时前
RV1126B 上支持的模型及全流程应用--从CNN及语音到 LLMVLM 与跨平台选型
linux·c语言·人工智能