简体   繁体   English

如何在 C++/C 中使用优先级队列对 function 进行排序?

[英]How can I sort function using priority queue in C++/C?

I want to array "functions" by priority我想按优先级排列“功能”

Eg SetNumber1 is first SetNumber2 is second ReadNumbers is last例如 SetNumber1 是第一个 SetNumber2 是第二个 ReadNumbers 是最后一个

//////////////// ////////////////

priority_queue < ??? > Q
Q.push(ReadNumbers());
Q.push(SetNumber2());
Q.push(SetNumber1());

i want to exec in order to SetNumber1(), SetNumber2(), ReadNumbers()我想执行 SetNumber1()、SetNumber2()、ReadNumbers()

Thanks.谢谢。

and sorry about my english skils, I'am korean, i'm not good at english对不起我的英语水平,我是韩国人,我不擅长英语

std::priority_queue works with a compare function which can't work with the given functions. std::priority_queue 与不能与给定函数一起工作的比较 function 一起工作。 You need to define your own priorities as an enum and then you can put the pair of the prio and function in an std::multimap so all functions can be called according to their prio.您需要将自己的优先级定义为枚举,然后您可以将 prio 和 function 这对放在 std::multimap 中,以便可以根据它们的 prio 调用所有函数。 You can put the pair also in a prio-q but then you still need a compare function that only works on the prio.您也可以将这对放在 prio-q 中,但您仍然需要一个仅适用于 prio 的比较 function。

eg:例如:

#include <iostream>
#include <map>
#include <functional>
    
enum class prio { HI, MID, LO };

int main()
{
    std::multimap<prio, std::function<void()>> prio_mmap;

    prio_mmap.insert(std::make_pair(prio::MID, []{ std::cout << "MID1\n"; }));
    prio_mmap.insert(std::make_pair(prio::LO, []{ std::cout << "LO\n"; }));
    prio_mmap.insert(std::make_pair(prio::HI, []{ std::cout << "HI\n"; }));
    prio_mmap.insert(std::make_pair(prio::MID, []{ std::cout << "MID2\n"; }));
    
    for (const auto& p: prio_mmap)
    {
        p.second();
    }
}

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

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