Ahh I figured out, I have to include that comparator in pop_heap too.
std heap sorting using custom > comparator
-
17-07-2023 - |
Pregunta
I'm trying to sort an integer array using std heap.
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct compare {
bool operator() (const int& s1, const int& s2) const{
if (s1 < s2) return true;
return false;
}
};
int main() {
vector<int> v;
v.push_back(8);
v.push_back(1);
v.push_back(3);
v.push_back(2);
v.push_back(4);
make_heap(v.begin(), v.end(), compare());
for (int i=0; i<5; i++) {
int t = v.front();
pop_heap(v.begin(), v.end()); v.pop_back();
cout << t << ' ';
}
cout << endl;
}
Now this sort outputs 8, 4, 3, 2, 1, which is correct.
But if I change s1 < s2 to s1 > s2 in the comparator function, the result becomes 1, 4, 8, 3, 2.
What am I doing wrong here?
Solución
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow