简体   繁体   English

priority_queue emplace给出分段错误

[英]priority_queue emplace gives segmentation fault

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. 我想要实现的是让优先级队列按tv.t的升序或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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM