I am supposed to implement the void pop_back (); function from the vector class for a project. Does anybody know how to implement this function that removes the last element from the Vect.
This is a discussion on pop_back() vector class within the C++ Programming forums, part of the General Programming Boards category; I am supposed to implement the void pop_back (); function from the vector class for a project. Does anybody know ...
I am supposed to implement the void pop_back (); function from the vector class for a project. Does anybody know how to implement this function that removes the last element from the Vect.
You implemented your own vector class? If so, how did you implement it?
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
The pop_back() function simply calls the destructor for the last element in the vector and updates the vector's internal state to have a size that is one smaller than it was before. How you do that in code depends on how vector is implemented. Even if you didn't write your own vector, each implementation can implement it differently, so there isn't really a single answer.
So say my private variables are
num // # of elements in the array
cap // size of the vector
T * data // the dynamic array
should I do something like
Or am I completely not understanding what you are telling me?Code:T * temp = new T[cap]; for (int i = 0; i < num - 1; ++i) { temp[i] = data[i]; } delete[] data; data = temp;
you could it that way but a more efficient method would be to call the destructor on the last element and then decrement num (making sure that the vector is not empty beforehand, of course).
Code:int main(void){srand(time(0));for(double l=rand(),l0=0,l00=0;;l0+=0.1){for(double l000=0;l000 <1;l000+=.001,l+=((double)rand()/RAND_MAX)/0x64,l00+=((sin(l*0x8*atan(l0)*l000-(l0*0x8*atan (l)))*0.5)+0.5)){l00-=floor(l00);for(size_t l0000=0,l00000=(size_t)(0x50*(l00));l0000<l00000;++l0000 )putchar(0x20);putchar(0x61+(int)((double)rand()/RAND_MAX*0x1a));putchar('\n');}}return 0;}
I'm having a hard time understanding what you are saying and putting that into code.
If num > 0, decrement num (i.e. --num) then call the destructor for data[num] (e.g. data[num].~T() ). If not, then either do nothing or indicate some error.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
>> I'm having a hard time understanding what you are saying and putting that into code.
Explicitly calling the destructor for an object is probably the way real implementations handle this, but it is a very advanced solution, so if your programming class isn't that advanced, then your original idea might be what the instructor is looking for. If you do use your original idea, remember that you must decrement cap.