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

文章描述了一个C++函数,用于在保持packet_seq顺序的前提下,高效地向列表中插入新的packet。函数考虑了插入位置的计算和多线程环境下的代码同步问题。
摘要由CSDN通过智能技术生成

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

即:

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

#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;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值