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;
}
```
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.