Instance variable value not printing properly

Viewed 69

I am using a constructor to initialize the instance variable. When I print the instance variable it gives wrong output.

int main(){
    int k[]={1,2,4};  
    int hs=3;  
    int n=3;  
    priorityq p(k,hs,n);  
    p.printKey();  
}  
class priorityq{  
    int key[];  
    int heapsize;  
    int n;  
public:  
    void printKey();  
    priorityq(int k[],int hs, int ni);  
};  
priorityq::priorityq(int k[],int hs, int ni){  
     for(int i=0;i<ni;i++)  
      key[i]=k[i];  
     heapsize=hs;   
     n=n_i;   
}
void priorityq::printKey(){     
     for(int i=0;i<heap_size;i++)   
       cout<<key[i]<<" ";   
     cout<<endl;    
}

I expect output to be 1 2 4 but am getting 3 3 4

2 Answers

Use std::array if you are using c++, or better for dynamic-ranged arrays, use std::vector. And instead of using []-operator use the at() method, which checks for out-of-bound errors:

Edit, there was an error in the constructor

int main(){
    std::vector<int> k{1,2,4};  
    int hs=3;  
    int n=3;  
    priorityq p(k,hs,n);  
    p.printKey();  
}  

..

class priorityq{  
    std::vector<int> key;  
    int heapsize;  
    int n;  
public:  
    void printKey();  
    priorityq(std::vector<int>& k,int hs, int ni);  
};  

..

priorityq::priorityq(std::vector<int>& k,int hs, int ni){  
     for(int i=0;i<ni;i++)  
      key.push_back(k.at(i));  
     heapsize=hs;   
     n=n_i;   
}
void priorityq::printKey(){     
     for(int i=0;i<heap_size;i++)   
       cout<<key.at(i)<<" ";   
     cout<<endl;    
}

You don't allocate any memory for the class member key.

Use std::vector<int> key; as the member instead, with a key.resize(ni); in your constructor.

Once you have it working, bin the whole thing, and use std::priority_queue.

Related