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.
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?
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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:#include <cmath> #include <complex> bool euler_flip(bool value) { return std::pow ( std::complex<float>(std::exp(1.0)), std::complex<float>(0, 1) * std::complex<float>(std::atan(1.0) *(1 << (value + 2))) ).real() < 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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
>> 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.