Connecting Tech Pros Worldwide Forums | Help | Site Map

a problem of iterator

Newbie
 
Join Date: Jul 2009
Posts: 16
#1: Jul 4 '09
string str="this IS A example";
for(string::iterator iter=str.begin();
iter!=str.end();++iter)
{
if(isupper(*iter))
{str.erase(iter);
--iter;}
}

cout<<str<<endl;
after "str.erase(iter);" i think iter will be an ivalidated iterator .But the code is correct.Why?Thank you~

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Jul 4 '09

re: a problem of iterator


Quote:

Originally Posted by evenstar View Post

string str="this IS A example";
for(string::iterator iter=str.begin();
iter!=str.end();++iter)
{
if(isupper(*iter))
{str.erase(iter);
--iter;}
}

cout<<str<<endl;
after "str.erase(iter);" i think iter will be an ivalidated iterator .But the code is correct.Why?Thank you~

On your implementation it seems to run but on other implementations it can make daemons fly out of your nose. Better make your loop do this:

Expand|Select|Wrap|Line Numbers
  1. for(string::iterator iter=str.begin(); iter!=str.end(); ) 
  2.    if (isupper(*iter))
  3.       iter= str.erase(iter);
  4.    else
  5.       iter++;
  6.  
kind regards,

Jos
Newbie
 
Join Date: Jul 2009
Posts: 16
#3: Jul 5 '09

re: a problem of iterator


I know use iterator like "iter= str.erase(iter);"is a good custom.But i puzzle that use a vector<int>::iterator like
Quote:
vec.erase(iter); //vec is a object of vector
iter--;
will lead a RUNTIME ERROR. Why this kind of error would not happen to object of string .(in Visual Studio 2008)
JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#4: Jul 5 '09

re: a problem of iterator


Quote:

Originally Posted by evenstar View Post

I know use iterator like "iter= str.erase(iter);"is a good custom.But i puzzle that use a vector<int>::iterator like

will lead a RUNTIME ERROR. Why this kind of error would not happen to object of string .(in Visual Studio 2008)

That can also happen with the string class, it depends on its implementation; suppose the string class reallocates its buffer after it had become less than half full; the buffer probably ends up somewhere else in memory leaving any pointers to the old buffer (kept by the iterator) invalid.

Simply assume that all iterators become invalid after an erase() operation and use the iterator returned by that erase() operation instead.

kind regards,

Jos
Newbie
 
Join Date: Jul 2009
Posts: 16
#5: Jul 5 '09

re: a problem of iterator


I see,and appreciate your help very much.
Reply