我正在尝试使用自定义比较器在 C++ 中构建整数对的优先级队列,其中第一个元素将按 降序 顺序排序,但如果两对的第一个元素相同,则第二个元素将按升序顺序排序。所以根据我的理解,下面的代码应该已经产生了想要的输出。
#include <bits/stdc++.h>
using namespace std;
// Custom comparator function for pairs of integers
struct Comp
{
bool operator()(pair<int, int> const& p1, pair<int, int> const& p2)
{
if (p1.first == p2.first)
{
// If the first elements are the same, sort in ascending order of the second elements
return p1.second < p2.second;
}
else
{
// If the first elements are different, sort in descending order
return p1.first > p2.first;
}
}
};
int main()
{
priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> pq;
pq.push(make_pair(3, 5));
pq.push(make_pair(2, 4));
pq.push(make_pair(1, 6));
pq.push(make_pair(3, 2));
pq.push(make_pair(2, 2));
while (!pq.empty())
{
pair<int, int> p = pq.top();
cout << p.first << " " << p.second << endl;
pq.pop();
}
return 0;
}
上面代码的期望输出应该是:
3 2
3 5
2 2
2 4
1 6
但是上面的代码产生了相反的输出:
1 6
2 4
2 2
3 5
3 2
也就是说,输出是 - 第一个元素按升序排序,如果对的第一个元素相同,则第二个元素按升序排序 - 这与我想要的输出正好相反.
我对此感到困惑,不知道我哪里出错了。我将不胜感激这背后的任何评论或逻辑,并感谢解决此问题的其他解决方案。谢谢!
更新#1: 我知道只需翻转我的比较器的运算符就可以解决问题。但是“p1.second > p2.second”不是降序排列的意思吗?我对整数对的向量做了同样的事情,它给了我正确的输出。
#include <bits/stdc++.h>
using namespace std;
// Custom comparator function for pairs of integers
bool comp (pair<int, int> const& p1, pair<int, int> const& p2)
{
if (p1.first == p2.first)
{
// If the first elements are the same, sort in ascending order of the second elements
return p1.second < p2.second;
}
else
{
// If the first elements are different, sort in descending order
return p1.first > p2.first;
}
}
int main()
{
vector<pair<int,int> > v;
v.push_back(make_pair(3, 5));
v.push_back(make_pair(2, 4));
v.push_back(make_pair(1, 6));
v.push_back(make_pair(3, 2));
v.push_back(make_pair(2, 2));
sort(v.begin(), v.end(), comp);
for(int i=0; i<v.size(); i++)
{
cout << v[i].first << " " << v[i].second << endl;
}
return 0;
}
它给我以下输出,根据逻辑是正确的。
3 2
3 5
2 2
2 4
1 6
因此,尽管具有相同的比较器功能逻辑(除了一个在 struct 内,另一个是直接的 function),为什么向量 one 在优先级队列的情况下给出正确的输出,它是以相反的意义工作?
我认为问题在于比较器的定义是,当第一个元素相同时,第一个元素按升序排序+第二个元素始终按升序排序。
试试
struct Comp
{
bool operator()(pair<int, int> const& p1, pair<int, int> const& p2)
{
if (p1.first == p2.first)
{
// If the first elements are the same, sort in ascending order of the second elements
return p1.second > p2.second; // Change this line
}
else
{
// If the first elements are different, sort in descending order
return p1.first < p2.first; // Change this line
}
}
};