c++ - Segmentation fault in LIS solution for Cracking the Coding interview 11.7 -
there problem in cracking coding interview -part v question 11.7 , solution trying implement here solution in java converted c++.but facing issue of segmentation fault.
#include<iostream> #include<vector> #include<algorithm> using namespace std; class htwt { public: int ht; int wt; htwt(int ht,int wt):ht(ht),wt(wt){} htwt(const htwt &other) { this->ht=other.ht; this->wt=other.wt; } bool operator<(const htwt& obj) const { cout << __func__ << std::endl; return (this->ht<obj.ht && this->wt<obj.wt); } }; typedef vector<htwt> vhtwt; typedef vector<vhtwt > vvhtwt; vhtwt& getseqwithmaxlen(vhtwt& seq1,vhtwt& seq2) { cout << __func__ << std::endl; if(seq1.empty()) return seq2; if(seq2.empty()) return seq1; return (seq1.size() > seq2.size() ? seq1 : seq2); } void lis(vhtwt& arr,vvhtwt& solutions,int current_index) { cout << __func__ << std::endl; if(current_index>arr.size()-1 || current_index<0) return; cout<<"arr.size()="<<arr.size()<<"current_index = "<<current_index<<endl; htwt cur_element = arr[current_index]; /* find longest sequence can append current_element */ vhtwt best_sequence; for(int i=0;i<current_index;i++) { cout<<"inside loop"<<endl; if (arr[i]<cur_element) best_sequence = getseqwithmaxlen(best_sequence,solutions[i]); //cout<<"{"<<best_sequence[best_sequence.size()-1].ht<<","<<best_sequence[best_sequence.size()-1].wt<<"}"<<" "; } /* append current_element */ vhtwt new_solution; if(!best_sequence.empty()) new_solution.insert(new_solution.end(),best_sequence.begin(),best_sequence.end()); new_solution.push_back(cur_element); /* add list , recurse */ solutions[current_index] = new_solution; lis(arr,solutions,current_index+1); } vhtwt lis(vhtwt& arr) { cout << __func__ << std::endl; vvhtwt solutions; lis(arr,solutions,0); vhtwt best_sequence; for(int i=0;i<arr.size();i++) best_sequence = getseqwithmaxlen(best_sequence,solutions[i]); return best_sequence; } vhtwt getlis(vhtwt& arr) { cout << __func__ << std::endl; // sort array either height or weight sort(arr.begin(),arr.end()); return lis(arr); } int main() { htwt arr[] = {htwt(12, 13), htwt(11, 15), htwt(9, 20), htwt(20, 20), htwt(40, 21), htwt(8, 42)}; vhtwt varr(arr,arr+(sizeof(arr)/sizeof(arr[0]))); vhtwt result = getlis(varr); for(int i=0;i<result.size();i++) cout<<"{"<<result[i].ht<<","<<result[i].wt<<"}"<<" "; cout<<endl; return 0; }
can please me tell why code crashing @ line
htwt cur_element = arr[current_index];
the size of arr 6 , index 0 , there should not segmentation fault guess.
$ ./a.out getlis operator< operator< operator< operator< operator< lis lis arr.size()=6current_index = 0 segmentation fault: 11
you not getting segmentation fault @ line
htwt cur_element = arr[current_index];
at
solutions[current_index] = new_solution;
because solutions
has not been initialized. change line
vvhtwt solutions;
to
vvhtwt solutions(arr.size());
Comments
Post a Comment