Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How string pop_back is implemented in constant time?

std::string pop_back() : Remove the last element of the string

In the C++ specification it is said that the C++11 string class function pop_back has a constant time complexity.

(to be more precise - Unspecified but generally constant)

http://www.cplusplus.com/reference/string/string/pop_back/

Apart from that I read the draft of C++11 specification and it is said that pop_back is equal to str.erase(str.length() -1). As far as I know the erase function simply allocates a new amount of memory and copies the remaining elements (not deleted) to this memory which will take up to linear time. In the light of this how can the pop_back finish in constant time.

like image 850
ralzaul Avatar asked Aug 15 '14 08:08

ralzaul


Video Answer


1 Answers

It does not have to reallocate.

The function probably just overwrites the last character with a zero and decrements some length information.

like image 158
Timbo Avatar answered Nov 10 '22 21:11

Timbo