繁体   English   中英

STL容器按优先级弹出pop()吗?

[英]STL container to pop() by priority?

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

对STL不太熟悉,按优先级弹出某些东西的最佳方法是什么? 优先级可能应该是MyRunnable imo的属性,但是在将可运行对象添加到队列时,我总是可以将该信息提供给STL容器。

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

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

不熟悉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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM