Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Time and Space Complexity of string class erase member function

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!

like image 420
B Stoops Avatar asked Oct 18 '18 03:10

B Stoops


People also ask

What is the time complexity of string erase?

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.

What is the time complexity of erase in string in C++?

std::string::erase in C++ Return value : erase() returns *this. Time Complexity : O(n) , n=length of string.

How do I remove a single character from a string in C++?

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.

What does .erase do in C++?

CPP. All elements are destroyed one by one. erase() function is used to remove elements from a container from the specified position or range.


1 Answers

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.

like image 103
Davis Herring Avatar answered Sep 26 '22 01:09

Davis Herring