Jak*_*lat 22 c++ heap stl min-heap comparator
我试图做一个最小堆1的longS IN C++使用STL make_heap等,但我比较似乎并不正确比较.以下是我目前的比较器:
struct greater1{
bool operator()(const long& a,const long& b) const{
return a>b;
}
};
Run Code Online (Sandbox Code Playgroud)
然而,当我std::pop_heap(humble.begin(),humble.end(),g);在那里g是一个实例greater1和humble一个堆谁使[9,15,15,25],当sort_heap被调用时,我得到一个15弹出.
我的比较器是否正确?可能出了什么问题?
编辑:
我意识到我正在运行没有比较器的sort_heap,而当我运行它这个比较器时,我得到[15,15,9,25]了sort_heap.现在我在想我的比较器肯定不起作用,但不确定原因.
1默认情况下,STL创建一个最大堆,所以我需要一个比较器.
per*_*eal 18
也许你在某处遗漏了某些东西,下面的代码按预期工作:
#include <vector>
#include <algorithm>
#include <iostream>
struct greater1{
bool operator()(const long& a,const long& b) const{
return a>b;
}
};
int main() {
std::vector<long> humble;
humble.push_back(15);
humble.push_back(15);
humble.push_back(9);
humble.push_back(25);
std::make_heap(humble.begin(), humble.end(), greater1());
while (humble.size()) {
std::pop_heap(humble.begin(),humble.end(),greater1());
long min = humble.back();
humble.pop_back();
std::cout << min << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22206 次 |
| 最近记录: |