c++ - The string erase() function is giving different results for similar calls -
i tried using string::erase() function 2 parameters start , end point giving me different results same type of call.
here code:
#include<iostream> using namespace std; int main(){ string s = "azxxzy"; s.erase(2,2); cout << s; s.erase(1,1); cout << endl << s; } it deletes 2 characters i.e xx first call second call deleting 1 z.
can please explain why happening?
corrected-
the question wrong used overloaded version i.e
'string& erase (size_t pos = 0, size_t len = npos); '
but expected output
'iterator erase(iterator first,iterator last)'
you're using std::string::erase() following synoptic:
string& erase (size_t pos = 0, size_t len = npos);
it erase part of string specified @ position pos length len. note position index pos begins 0. default parameter len = npos indicates characters until end.
in example means:
string s = "azxxzy"; s.erase(2,2); /* azzy: deleting 2 characters position 2 */ s.erase(1,1); /* azy: deleting 1 character position 1 */ in textbook written 2 parameters of
std::string::eraseiterator first,iterator last. why assumed giving strange result.
you mean overloaded version:
iterator erase (iterator first, iterator last); but didn't provide iterator. you're passing int literals implicitly converted size_t. in link i've posted above can see overloaded version + example.
i expected output 'ay'
to output iterators following std::string::begin() , std::string::end():
string s = "azxxzy"; s.erase(s.begin() + 1, s.end() - 1); /* ay: deleting characters */ /* between 1st , last character */
Comments
Post a Comment