c++ - Segmentation fault when declaring a vector -
i'm writing programme 2 classes:
class sequence { protected: vector<int> seq_; public: sequence(){ for(int i=0; i<16;i++) seq_.push_back(0); }; sequence(int a, int b,int c){ for(int i=0; i<16; i++) seq_.push_back(a*i+b*i*i+c*i*i*i); }; sequence(const sequence & myseq){ for(int i=0; i<16;i++) seq_[i]=myseq.get_i(i); }; int get_i(int i)const{ return seq_[i]; }; void print() const { for(int i=0; i<16; i++) cout<<seq_[i]<<endl; }; int operator*(sequence & myseq) const { int sum=0; for(int i=0; i<16;i++) sum+=seq_[i]*myseq.seq_[i]; return sum; }; void operator=(sequence & myseq) { for(int i=0; i<16; i++) seq_[i]=myseq.seq_[i]; }; };
this first class devoted containing sequence , overloading basics operators. following, on other side, contains binary sequence corresponding number (or random binary sequence if default constructor gets call).
class binary : public sequence { private: public: binary(){ for(int i=0; i<16; i++) seq_.push_back(round(drand48())); }; binary(int num){ double prec=num; double last=0; for(int i=16; i>=0; i--){ prec=prec-last; if(int(prec/pow(2,i))==0){ seq_.push_back(0); last=0; }else{ seq_.push_back(1); last=pow(2,i); } } }; binary not_ () { binary mybin; for(int i=0; i<16; i++){ if( seq_[i]==1){ mybin.seq_[i]=0; }else{ mybin.seq_[i]=1; }; }; return mybin; }; int cost (sequence myseq){ int k=myseq*(*this)-(binary::not_())*myseq; return k; }; };
the problem segmentation fault defining vector:
vector<binary> mybins (pow(2,16));
i ran gdb , stuck @ copy constructor:
sequence(const sequence & )
i wondering if give me find error , explain me. i'm guessing has poor knowledge of how standard library works! thank time.
sequence(const sequence & myseq){
this constructor. constructing new object.
for(int i=0; i<16;i++) seq_[i]=myseq.get_i(i);
the seq_
member empty vector. attempting set nonexistent values in vector undefined behavior, , reason crash. other constructors use push_back()
, correctly, insert new values vector. should done here well.
Comments
Post a Comment