【发布时间】:2020-08-13 06:16:59
【问题描述】:
以下代码使用与向量和优先级队列相同的比较器功能。然而,两种数据结构产生的顺序是不同的。我希望优先级队列的行为方式与向量相同。
我有两个问题
- 为什么顺序不同?
- 如何使优先队列的顺序与向量相同?
这是以下代码的输出:
//Please ignore extra header files, I know I don't need them.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
#include <stack>
#include <iterator>
#include <unordered_map>
#include <functional>
using namespace std;
class Solution {
public:
typedef pair<string, int> PII;
static bool cmp(const PII& a, const PII& b)
{
if (a.second == b.second)
return a.first < b.first;
return a.second > b.second;
}
void func(vector<string>& words)
{
unordered_map<string, int> hMap;
for (const auto& w : words)
hMap[w]++;
std::priority_queue< PII, std::vector<PII>, std::function<bool(PII, PII)> > Q(cmp);
vector<PII> V;
for (const auto& e : hMap)
{
Q.emplace(e);
V.emplace_back(e);
}
std::sort(V.begin(), V.end(), cmp);
//Now why does order of elements is different in vector V and priority_queue Q, despite using same comparator function?
int size = Q.size();
cout << "Order in priority Queue:" << endl;
for (int i = 0; i < size; i++)
{
PII e = Q.top();
cout << e.first << ":" << e.second << endl;
Q.pop();
}
cout << "Order in vector:" << endl;
for (const auto& e : V)
{
cout << e.first << ":" << e.second << endl;
}
}
};
int main()
{
Solution s;
vector<string> words = {"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is" , "we" , "we" , "we" };
s.func( words );
return 0;
}
【问题讨论】:
-
引自cpreference "请注意,比较参数的定义是,如果它的第一个参数在弱排序的第二个参数之前,它会返回true。但是因为优先级队列首先输出最大的元素, “之前”的元素实际上是最后输出的。”
-
@Evg 为什么它被关闭为重复?我知道如何将比较器用于最小堆。这个问题是关于两种数据结构解释比较器的方式。
标签: c++ vector comparator priority-queue