I wanted to know if someone knew the implementation of the C++ string::erase function and it's complexity. I know the C++ string is an object of characters. I'm assuming it doesn't allocate and create a new object of characters and then copy over the characters from the old string O(n) and O(n) space. Does it shift over the characters O(n) and O(1) space? I've looked on cplusplus.com and Bjarne Stroustrup book but haven't been able to find the answer. Can someone point me to the source code where it's implemented or know the answer?
Thanks!
Its time complexity is O(1). erase(): Deletes a substring of the string. Its time complexity is O(N) where N is the size of the new string.
std::string::erase in C++ Return value : erase() returns *this. Time Complexity : O(n) , n=length of string.
Master C and Embedded C Programming- Learn as you go In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed.
CPP. All elements are destroyed one by one. erase() function is used to remove elements from a container from the specified position or range.
As stated in the comments, the standard doesn't specify any complexity requirements for many basic_string
functions (including erase
). This is partly because there have historically been a number of different implementation strategies (most famously, copy-on-write was popular in the C++98 era), so the committee was reluctant to specify anything too precisely.
The basic behavior of typical, modern implementations is very much like vector<char>
: insertion and deletion are cheap at the end (with amortized reallocations) and expensive at the beginning. Small strings are handled without memory allocation at all (by reusing the pointers' space to store the characters). This means that erasure can result in copying the whole string if it becomes very short (but then the copy is cheap). It also means that iterators and references are invalidated more easily than with vector
.
There aren't any algorithms that perform better on a string
, but there are alternate data structures that have different performance characteristics. The rope is typical among these in that it provides somewhat slower access but much faster insertion and deletion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With