简体   繁体   English

比较 priority_queue/stl 中的 function

[英]Compare function in priority_queue/stl

 bool operator() (const pair<int,string>& a,const pair<int,string>& b){
        if(a.first!=b.first)
            return a.first>b.first;
        else
            return a.second < b.second;
    }

i have been doing heap problems, found out about this comparator function, here its comparing frequency of 2 words, but im not getting how exactly does it work and can't find any appropriate explanation of it.我一直在做堆问题,发现了这个比较器 function,这里它比较了 2 个单词的频率,但我不知道它到底是如何工作的,也找不到任何合适的解释。 Could someone please explain it in a simple way?有人可以用简单的方式解释一下吗? Thank you.谢谢你。

The comparison function sorts on the int s first in descending order.比较 function 按降序对int排序。 If two compared int s are the same, it'll do a lexicographical comparison of the string s and sort on those in ascending order.如果两个比较的int相同,它将对string s 进行字典顺序比较,并按升序对它们进行排序。

Example, given a container with this content:例如,给定一个包含此内容的容器:

std::vector<std::pair<int, std::string>> vec{
    {1, "F"}, {2, "E"}, {3, "D"}, {4, "C"}, {5, "B"}, {6, "A"},
    {1, "A"}, {2, "B"}, {3, "C"}, {4, "D"}, {5, "E"}, {6, "F"},
};

Using a standard std::sort with your comparison function would produce this order:使用标准std::sort与您的比较 function 将产生以下顺序:

6 A
6 F
5 B
5 E
4 C
4 D
3 C
3 D
2 B
2 E
1 A
1 F

For a std::priority_queue the extraction order will be the reverse since it puts the largest value on top and your comparison function says that a smaller number has higher priority than a larger number.对于std::priority_queue ,提取顺序将相反,因为它将最大值放在最前面,而您的比较 function 表示较小的数字比较大的数字具有更高的优先级。

Demo with debug prints带有调试打印的演示

Note that I used std::tie in the demo.请注意,我在演示中使用了std::tie It is often preferred when creating comparison functions that are required to do strict weak ordering because it makes it a lot easier to avoid making mistakes.在创建需要执行严格弱排序的比较函数时,它通常是首选,因为它可以更容易地避免犯错误。 It does the same as your original though:它与你原来的一样:

bool operator()(const std::pair<int, std::string>& a,
                const std::pair<int, std::string>& b) 
{
    return std::tie(b.first, a.second) < std::tie(a.first, b.second);
}

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

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