The following code gives segmentation fault, could someone enlighten me? All I wanted to achieve is to have a priority queue sorted with ascending order of tv.t or descending order of tv.m.
struct tv {
int m;
int c;
int t;
tv(int mm, int cc, int tt): m(mm), c(cc), t(tt) {}
};
bool comp(struct tv & t1 , struct tv & t2) {
if (t1.t == t2.t) {
return t1.m < t2.m;
}
return t1.t > t2.t;
}
int main(int argc, char** argv) {
priority_queue<struct tv, vector<struct tv>, decltype(&comp)> q;
q.emplace(0, 0, 0);
q.emplace(1, 0, 0);
q.emplace(1, 1, 1);
q.emplace(1, 2, 0);
return 0;
}
You gave your priority queue a comparator type in the template argument list, but you didn't give it an actual comparator in the constructor.
priority_queue<tv, vector<tv>, decltype(&comp)> q(comp);
As you have it, it is calling a null function pointer. This is one nice thing about using function objects instead of function pointers. They can be default constructed and do the right thing.
struct comp_t {
bool operator()(const tv & t1 , const tv & t2) const {
if (t1.t == t2.t) {
return t1.m < t2.m;
}
return t1.t > t2.t;
}
};
priority_queue<tv, vector<tv>, comp_t> q;