Home > Enterprise >  Got an error while compiling this code for K sorted array problem solved
Got an error while compiling this code for K sorted array problem solved

Time:10-27

i was doing this question where we need to sort k sorted arrays in a single array and compiler threw an error:

"prog.cpp:20:23: error: expected ) before & token struct mycomp(triplet &t1 , triplet &t2){"

I am a begginner can someone help me understand whats the issue.

`` code ```

struct triplet{
    int val; int apos; int valpos;
};
struct mycomp(triplet &t1 , triplet &t2){
    bool operator(triplet &t1 , triplet &t2){
        return t1.val<t2.val;
}
};

class Solution
{
    public:
    //Function to merge k sorted arrays.
    vector<int> mergeKArrays(vector<vector<int>> arr, int K)
    {
        //code here
        vector<int> v;
        priority_queue<triplet , vector<triplet> ,mycomp) pq;
        
        for(int i=0; i<k; i  ){
            triplet t = {arr[i][0] , i ,0}
            pq.push_back(t);
        }
        
       while(pq.empty()==false){
               triplet t = pq.top(); pq.top();
               v.push_back(t.val);
               int ap == curr.apos; int vp = curr.valpos;
               if(vp 1<arr[ap].size()){
                   triplet t = (arr[ap][vp 1] , ap , vp 1);
                   pq.push(t);
               }
           }
       
    
    return v;
    }
    
};

CodePudding user response:

There are many other errors/mistakes in your given program. The one you mentioned is because mycomp is a struct and so while writing its definition you can't pass parameters to it(since it is not a function definition). This particular error can be fixed by changing mycomp definition to:

//mycomp is  a struct and not a function so don't pass parameters
struct mycomp{
    bool operator()(triplet &t1 , triplet &t2)//note the parenthesis () i have added to overload operator()
    {
        return t1.val<t2.val;
    }
};

Also for how to use std::priority_queue correctly you can refer to this.

  • Related