Using Lint it repeatedly objects to using clear on a std string and wants to suggest using the erase method with no parameters.
Looking at the documentation both with do what I desire and that is to resize the string to zero elements so that the string is empty with no elements. I do not want to delete the string at this point simply remove all members from it.
My question is what is the difference between the two methods and does anyone know the reason I SHOULD be using erase over the clear method ?
The C++ string library allows you to erase a part of a string using the erase() function.
Syntax 4: Erase the single character at iterator position pos. string& string ::erase (iterator pos) - Return the first character after the last character removed - If no such character is remaining then, returns string::end() i.e. position after the last character.
All elements are destroyed one by one. erase() function is used to remove elements from a container from the specified position or range. Syntax : 1.
string& string ::erase (iterator pos) - Return the first character after the last character removed - If no such character is remaining then, returns string::end () i.e. position after the last character. string str ("Hello World!"); Before erase : Hello World! After erase : Hell World! 5.
string& string ::erase (iterator beg, iterator end ) - Erases all characters of the range [ beg, end) - Returns end i.e. the first character after the last character removed. - If no such character is remaining then, returns string::end () i.e. position after the last character string str ("Hello World!"); Before erase : Hello World!
std::string::erase in C++. The function erases a part of the string content, shortening the length of the string. The characters affected depend on the member function version used: Return value : erase() returns *this.
If you want to still show these messages and leave side effects (not recommended), remember to use the ‘no-console’ comment to avoid lint from spitting out an error; The lint message: error Missing an explicit type attribute for button react/button-has-type.
I cannot see a single reason for this. Quite the opposite: I actually had to look into the reference to see whether erase()
can be called without arguments. erase()
is used to remove some specified characters from the string. clear()
is used to remove the entire contents of the string (but not its capacity).
The general programming rule is "write what you mean." If you want to clear the entire string, use the function for it: clear()
.
Furthermore, in the general case, erase()
has more work to do—it must check that the index is in range, and throw an exception if not. clear()
is guaranteed non-throwing. Clever optimisers might make them identical, but I would consider using erase()
instead of clear()
"premature" pessimisation.
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