c++ - Increase capacity for vector -
disclaimer 1 - i'm new programming disclaimer 2 - have searched , searched, can't find i'm looking for.
for project, more or less re-writing vector class in more stripped down form. part i'm hung writing push_back method. all's until have increase capacity of array.
i assume should done create new vector increased size, , copy elements old vector new one, use assignment operator assign oldvector newvector.
i have either written push_back method incorrectly, overloaded = operator incorrectly, or else i'm lacking in understanding on should happening. appreciated.
when compiling, error "lvalue required left operand of assignment" on line assign = tempv
template <class t> vector<t>& vector<t>::operator = (const vector<t> & v) { int newsize = v.size(); int newcapacity = v.getcapacity(); data = new t[newcapacity]; for(int = 0; < newsize; i++) data[i] = v.data[i]; return *this; } template <class t> void vector <t> :: push_back(const t & number) { if(numitems == capacity) { vector <t> tempv(this->capacity * 2); for(int = 0; < numitems; i++) tempv.data[i] = data[i]; *this = tempv; } if(numitems < capacity) data[numitems++] = number; }
update see why code wouldn't compile while using
*this = tempv;
in copy method, using v.size , not v.size() method. after fixing that, code compiles , runs, capacity of vector same , did not increase expecting. i'm still missing something. code above has been updated.
thanks again any/all help!
why have create new vector<t>
? create new array:
template <class t> void vector <t> :: push_back(const t & number) { if(numitems == capacity) { capacity *= 2; t* newdata = new t[capacity]; std::copy(data, data + numitems, newdata); delete[] data; data = newdata; } data[numitems++] = number; }
Comments
Post a Comment