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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With