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;
}
相关推荐
不想写代码的星星1 天前
std::function 详解:用法、原理与现代 C++ 最佳实践
c++
樱木Plus3 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
RuoZoe5 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
blasit5 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_6 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星6 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛8 天前
delete又未完全delete
c++
祈安_8 天前
C语言内存函数
c语言·后端
端平入洛9 天前
auto有时不auto
c++
norlan_jame10 天前
C-PHY与D-PHY差异
c语言·开发语言