c++ - arrays, removeFirst() not working? -
i have created method should remove first element of array, when run code, debugger flips out , i'm not sure why.
this removefirst() method:
loan & listofloans :: removefirst(){ index = 0; //determine if container needs shrunk if((numberofelements < capacity/4) && (capacity >= 4)){ // shrink container when array 1/4 full cout<<"shrinking array! \n"; loan ** temp = elements; elements = new loan * [numberofelements/2]; //copy temp array elements for(int = 0; i<numberofelements; i++){ temp[i] = elements[i]; numberofelements = numberofelements/2; delete [] temp; } } numberofelements--; return **elements; }
and header file measure:
#include <iostream> #include "loan.h" using namespace std; class listofloans { public: listofloans(int initial_size=4); ~listofloans(void); void add(loan & aloan); loan & first() ; loan & removefirst(); // answer first element list , remove list // if resulting list more 3 quarters empty release memory loan & removelast(); // answer last element list , remove list // if resulting list more 3 quarters empty release memory loan & next(); int size(); private: loan ** elements; //actuall stuff in array m_pndata; int numberofelements; //number of elements in list stize of array? m_nlength int capacity; //size of available array memory int index; //used iteration };
there many issues code. here annotated copy.
// return reference cannot used if removing element. // looks java-ism. loan & listofloans :: removefirst(){ // unused variable index = 0; if((numberofelements < capacity/4) && (capacity >= 4)){ cout<<"shrinking array! \n"; loan ** temp = elements; // allocating array of size numberofelements/2... elements = new loan * [numberofelements/2]; // accessing elements way past end. for(int = 0; i<numberofelements; i++){ temp[i] = elements[i]; // halving array size in every iteration numberofelements = numberofelements/2; // deleting temp in every iteration, // causing double-frees delete [] temp; } } // if array not need shrunk, // removing last element. // removed element not freed , leaking. numberofelements--; // returning first element, // not removed. return **elements; }
i recommend replace listofloans
stl container, such std::deque
. if can't this, here minimal fixed version.
loan listofloans::removefirst() { loan to_return; if (numberofelements == 0) { return to_return; // return default value, there nothing remove } if ((numberofelements < capacity/4) && (capacity >= 4)) { loan **old = elements; capacity = capacity / 2; elements = new loan*[capacity]; (int i=0; < numberofelements - 1; ++i) { elements[i] = old[i+1]; } to_return = *old[0]; delete old[0]; delete[] old; } else { to_return = *elements[0]; delete elements[0]; (int i=0; < numberofelements - 1; ++i) { elements[i] = elements[i+1]; } } --numberofelements; return to_return; }
Comments
Post a Comment