Reputation: 3
string s;
cin>>s;
string::iterator it;
it=s.begin();
s.push_back('0');
s.erase(it);
cout<<s<<endl;
everytime I input a 4-letter string such as "milk",it turns out to be core dumped . Other words with more or less than 4 letters can work well. What's wrong ?
Upvotes: 0
Views: 206
Reputation: 264571
Modifying a string invalidates any iterators that were generated from the string.
Technically they are only invalidated only if the string re-sizes.
But unless you take explicit precautions to prevent the string re-sizing you must assume that any iterators are invalidated when you add content to the string that increases the size.
See: www.sgi.com/tech/stl/basic_string.html
Note also that, according to the C++ standard, basic_string has very unusual iterator invalidation semantics. Iterators may be invalidated by swap, reserve, insert, and erase (and by functions that are equivalent to insert and/or erase, such as clear, resize, append, and replace).
Additionally, however, the first call to any non-const member function, including the non-const version of begin() or operator[], may invalidate iterators. (The intent of these iterator invalidation rules is to give implementors greater freedom in implementation techniques.) In this implementation, begin(), end(), rbegin(), rend(), operator[], c_str(), and data() do not invalidate iterators.
Upvotes: 1
Reputation: 12117
try to assign the iterator after you add 0
to the end
string s;
cin>>s;
s.push_back('0');
string::iterator it;
it=s.begin();
s.erase(it);
cout<<s<<endl;
Upvotes: 4