关于使用我自己创建的类使用优先级队列的问题

时间:2019-05-28 00:54:16

标签: c++ c++14

我创建了一个三元组类,并希望将其对象用作“最小优先级”队列中的成员,但出现错误。该代码用于合并k个排序的数组。 请帮助我解决这个疑问。我尝试了多种方法来解决此问题,但大多数情况下都会出错。

    #include<queue>
    using namespace std;

    class triplet{
        public:
        int element;
        int ai;
        int ei;
        bool operator()(triplet &a, triplet &b);
    };


    class Comp{
        public:
        bool operator()(triplet &a, triplet &b){    
            return a.element > b.element;       
        }
    };

    vector<int> mergeKSortedArrays(vector<vector<int>*> input){
        /* Don't write main().
         * Don't read input, it is passed as function argument.
         * Return the output.
         * Taking input and printing output is handled automatically.
         */
        vector<int> ans;
        priority_queue<triplet , vector<triplet> , Comp> pq;

        for(int i = 0; i < input.size(); i++){
            triplet *temp = new triplet();
            temp->element = input[i]->at(0);
            temp->ai = i;
            temp->ei = 0;
            pq.push(temp);
        }

        while(!pq.empty()){
            triplet current = pq.top();
            ans.push_back(current);
            pq.pop();

            if(current.ei < input[current.ai]->size())
                pq.push_back(input[current.ai]->at(current.ei + 1) , current.ai , ei + 1);
        }
        return ans;
    }

Compilation Failed
In file included from Runner.cpp:4:0:
Solution.h: In function 'std::vector mergeKSortedArrays(std::vector*>)':
Solution.h:34:21: error: no matching function for call to 'std::priority_queue, Comp>::push(triplet*&)'
         pq.push(temp);
                     ^
In file included from /usr/include/c++/5/queue:64:0,
                 from Solution.h:1,
                 from Runner.cpp:4:
/usr/include/c++/5/bits/stl_queue.h:499:7: note: candidate: void std::priority_queue<_Tp, _Sequence, _Compare>::push(const value_type&) [with _Tp = triplet; _Sequence = std::vector; _Compare = Comp; std::priority_queue<_Tp, _Sequence, _Compare>::value_type = triplet]
       push(const value_type& __x)
       ^
/usr/include/c++/5/bits/stl_queue.h:499:7: note:   no known conversion for argument 1 from 'triplet*' to 'const value_type& {aka const triplet&}'
/usr/include/c++/5/bits/stl_queue.h:507:7: note: candidate: void std::priority_queue<_Tp, _Sequence, _Compare>::push(std::priority_queue<_Tp, _Sequence, _Compare>::value_type&&) [with _Tp = triplet; _Sequence = std::vector; _Compare = Comp; std::priority_queue<_Tp, _Sequence, _Compare>::value_type = triplet]
       push(value_type&& __x)

1 个答案:

答案 0 :(得分:1)

temptriplet指针,但是您的优先级队列存储三元组对象。将temp更改为triplet temp;(进行其他适当的代码更改)。或给triplet构造函数,完全摆脱temp,而改用pq.emplace(/*...*/);