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.

Printable View

- 04-23-2006noodle24pop_back() vector class
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.

- 04-23-2006laserlight
You implemented your own vector class? If so, how did you implement it?

- 04-23-2006Daved
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.

- 04-24-2006noodle24
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

Code:`T * temp = new T[cap];`

for (int i = 0; i < num - 1; ++i)

{

temp[i] = data[i];

}

delete[] data;

data = temp;

- 04-24-2006Sebastiani
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).

- 04-24-2006noodle24
I'm having a hard time understanding what you are saying and putting that into code.

- 04-24-2006laserlight
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.

- 04-24-2006Daved
>> 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.