STL容器按优先级到pop()?

发布于 2024-08-30 07:37:24 字数 159 浏览 2 评论 0原文

我正在为 Qt 编写一个线程池,因为 QRunnable 不处理新线程中的事件循环。

对 STL 不太熟悉,按优先级 pop() 某些内容的最佳方法是什么?在我看来,优先级可能应该是 MyRunnable 的一个属性,但在将可运行对象添加到队列时,我始终可以将该信息提供给 STL 容器。

I'm writing a thread-pool for Qt as QRunnable doesn't handle event loops in new threads.

Not too familiar with STL, what would be the best way to pop() something by priority? Priority should probably be a property of MyRunnable imo, but I can always give that info to an STL container when adding the runnable to the queue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

澉约 2024-09-06 07:37:24

通过 pop() 我假设您想要某种堆栈结构。我不确定如何使用堆栈语义来实现这一点,但是可以使用 std::priority_queue 简单地解决优先级问题。

By pop() I'm assuming you want some sort of a stack structure. I'm unsure how to achieve that with stack semantics, but the priority issues could be solved simply with std::priority_queue.

你怎么敢 2024-09-06 07:37:24

标准库有 std::priority_queue,顾名思义,它是一个通用优先级队列实现。

The standard library has std::priority_queue, which is, as its name suggests, a generic priority queue implementation.

不必在意 2024-09-06 07:37:24

不熟悉 QT,但正如其他人建议的那样,使用 priority_queue

您还需要一个函子来允许结构访问优先级信息并指定排序顺序。

struct is_higher_priority {
    bool operator()( MyRunnable const &l, MyRunnable const &b )
        { return l.priority > r.priority; }
};

std::priority_queue< MyRunnable, std::deque<MyRunnable>, is_higher_priority > q;

...

q.push( task_1 );
q.push( task_2 );
q.push( task_3 );

MyRunnable &highest = q.top();
highest.run();
q.pop();

Not familiar with QT, but as other suggest, use a priority_queue.

You'll also need a functor to allow the structure to access the priority information and specify the sorting order.

struct is_higher_priority {
    bool operator()( MyRunnable const &l, MyRunnable const &b )
        { return l.priority > r.priority; }
};

std::priority_queue< MyRunnable, std::deque<MyRunnable>, is_higher_priority > q;

...

q.push( task_1 );
q.push( task_2 );
q.push( task_3 );

MyRunnable &highest = q.top();
highest.run();
q.pop();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文