常量表达式中的非文字类型“比较”

时间:2019-04-18 14:45:00

标签: c++ c++14

为priority_queue构造自己的比较类,但是,我无法弄清楚为什么消息继续显示非文字类型

如果您想查看我的代码在做什么,请参见以下说明:

将K个排序间隔列表合并为一个排序间隔列表。您还需要合并重叠的间隔。

class compare {
private:
    vector<vector<Interval>> tmp;
public:
    compare (vector<vector<Interval>> &intervals) {
        tmp = intervals;
    }
    bool operator() (const pair<int, int> &a, const pair<int, int> &b) {
        return tmp[a.first][a.second].start > tmp[b.first][b.second].start;
    }
};


class Solution {
public:
    vector<Interval> mergeKSortedIntervalLists(vector<vector<Interval>> &intervals) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, compare(intervals)> pq;

        for (int i = 0; i < intervals.size(); i++) {
            if (!intervals[i].empty()) {
                pq.push(make_pair<i, 0>);
            }
        }
        vector<Interval> res;
        while(!pq.empty()) {
            pair<int, int> node = pq.top();
            pq.pop();
            res.push_back(intervals[node.first][node.second]);
            node.second++;
            if(node.second < intervals[node.first].size()) {
                pq.push(make_pair(node.first, node.second));
            }
        }
        return mergeInterval(res);
    }

private:
    vector<Interval> mergeInterval (vector<Interval> &res) {
        if(res.empty() || res.size() == 1) return res;
        vector<Interval> ans;

        int start = res[0].start;
        int end = res[0].end;
        for (auto interval : res) {
            if(interval.start <= end) {
                end = max(interval.end, end);
            }else {
                ans.push_back({start, end});
                start = interval.start;
                end = interval.end;
            }
        }
        ans.push_back({start, end});
        return ans;
    }

};

错误消息: 非文字类型“ compare”的临时变量,位于常量表达式中priority_queue,vector>,compare(intervals)> pq;

1 个答案:

答案 0 :(得分:2)

我看到代码有两个问题:

  1. priority_queue<pair<int, int>, vector<pair<int, int>>, compare(intervals)> pq;应该是 priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq{compare(intervals)};

  2. make_pair<i, 0>应该是make_pair(i, 0)

至少it compiles