0

I am trying to solve merge k sorted arrays into a single array using heap. But i am getting a ERROR: compiling failed with exit code 1.I don't understand what this means.

Compiling failed with exit code 1, compiler output: I am not able to understand the error I guess there is a problem with priority queue working. As i am new to this please someone suggest the changes.

I have tried using std:: pair inbuilt in stl and it works fine for that. but if i define a class like in the code it is not working

class pairr{
    public:
        int data;
        int id;
        int index;

    pairr(int data,int id,int index){
        this->data=data;
        this->id=id;
        this->index=index;
    }
};


vector<int> merge(vector<vector<int>> &V){

    priority_queue<pairr,vector<pairr>,greater<pairr>> q;

    vector<int> out;


    //creating min heap of k nodes
    for(int i=0;i<V.size();i++){
        pairr a(V[i][0],i,0);
        q.push(a);        
    }

    while(!q.empty()){
        //minimum element
        pairr cur=q.top();

        // i=array of min ele j=index of array
        int i=cur.id;
        int j=cur.index;

        //pop the element and push it in output array
        q.pop();
        out.push_back(cur.data);

        //push new element from same array
        if(j+1<V[i].size()){ 
            pairr a(V[i][j+1],i,j+1);
            q.push(a);
        }

        //return the output vector
        return out;
    }

}

int main() {
    vector<vector<int>> V={{0,4,10,12},
                 {1,3,5,7},
                 {2,4,12,15,20}};

    vector<int> output=merge(V);
    for(int i=0;i<output.size();i++){
        cout<<output[i]<<" ";
    }

    return 0;
}
```
  • Unrelated to your problem, but please read [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) If you stop doing it you could give your own classes more natural names like `pair` instead of `pairr` (even though naming something the same as a standard class/function is somewhat confusing anyway, especially since your `pairr` class isn't really a "pair"). – Some programmer dude Jul 07 '19 at 18:45
  • _"I am not able to understand the error"_ -- and that is why you are asking about it, right? So why not copy the error message into your question so that people who might understand the error can see it? – JaMiT Jul 08 '19 at 06:02
  • Thank you,from next time I will take care of that. – Raghvendra singh Jul 08 '19 at 12:10

1 Answers1

1

You need to provide a way to compare two instances of pairr. How else would std::priority_queue know which pairr is of higher or lower priority than the other? Since you want to use greater<pairr>, you should implement operator>().

It works for std::pair because std::pair does in fact provide various comparison operators, operator> among them.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85