c++ 为什么 priority_queue greater<> 结果与 sort`s greater 结果不同?
c++ why priority_queue greater<> result is different from sort`s greater result?
我搜索了类似的内容,但我看不懂答案,所以我再问你。
vector<int> v;
v.push_back(3);
v.push_back(11);
v.push_back(13);
v.push_back(-1);
v.push_back(-8);
v.push_back(324);
v.push_back(55);
sort(v.begin(),v.end(), greater<int>() );
for(auto i : v)
{
cout << i << " ";
}
//结果降序
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(3);
pq.push(5);
pq.push(4);
pq.push(9);
pq.push(13);
pq.push(15);
while(!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
//结果是升序
此处还提供了更大的实现
struct greater : public binary_function<_Tp, _Tp, bool>
{
_GLIBCXX14_CONSTEXPR
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x > __y; }
}
x > y 表示降序,但为什么呢??为什么特别是在优先级队列中更大意味着升序?请有人澄清这一点..谢谢.
来自this std::priority_queue
reference:
A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element
[强调我的]
因此使用 std::less
的默认排序是降序。通过使用 std::greater
你可以逆转它。订购。
因为它是这样定义的。之前的答案很好,但我会更加强调 specification
的另一部分
Note that the Compare parameter is defined such that it returns true
if its first argument comes before its second argument in a weak
ordering. But because the priority queue outputs largest elements
first, the elements that "come before" are actually output last. That
is, the front of the queue contains the "last" element according to
the weak ordering imposed by Compare.
所以在“大”的情况下,它意味着“先小”。
我搜索了类似的内容,但我看不懂答案,所以我再问你。
vector<int> v;
v.push_back(3);
v.push_back(11);
v.push_back(13);
v.push_back(-1);
v.push_back(-8);
v.push_back(324);
v.push_back(55);
sort(v.begin(),v.end(), greater<int>() );
for(auto i : v)
{
cout << i << " ";
}
//结果降序
priority_queue<int, vector<int>, greater<int>> pq;
pq.push(3);
pq.push(5);
pq.push(4);
pq.push(9);
pq.push(13);
pq.push(15);
while(!pq.empty())
{
cout << pq.top() << " ";
pq.pop();
}
//结果是升序
此处还提供了更大的实现
struct greater : public binary_function<_Tp, _Tp, bool>
{
_GLIBCXX14_CONSTEXPR
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x > __y; }
}
x > y 表示降序,但为什么呢??为什么特别是在优先级队列中更大意味着升序?请有人澄清这一点..谢谢.
来自this std::priority_queue
reference:
A priority queue is a container adaptor that provides constant time lookup of the largest (by default) element
[强调我的]
因此使用 std::less
的默认排序是降序。通过使用 std::greater
你可以逆转它。订购。
因为它是这样定义的。之前的答案很好,但我会更加强调 specification
的另一部分Note that the Compare parameter is defined such that it returns true if its first argument comes before its second argument in a weak ordering. But because the priority queue outputs largest elements first, the elements that "come before" are actually output last. That is, the front of the queue contains the "last" element according to the weak ordering imposed by Compare.
所以在“大”的情况下,它意味着“先小”。