a problem of iterator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • evenstar
    New Member
    • Jul 2009
    • 30

    a problem of iterator

    string str="this IS A example";
    for(string::ite rator iter=str.begin( );
    iter!=str.end() ;++iter)
    {
    if(isupper(*ite r))
    {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?Tha nk you~
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by evenstar
    string str="this IS A example";
    for(string::ite rator iter=str.begin( );
    iter!=str.end() ;++iter)
    {
    if(isupper(*ite r))
    {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?Tha nk 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:

    Code:
    for(string::iterator iter=str.begin(); iter!=str.end(); ) 
       if (isupper(*iter))
          iter= str.erase(iter);
       else
          iter++;
    kind regards,

    Jos

    Comment

    • evenstar
      New Member
      • Jul 2009
      • 30

      #3
      I know use iterator like "iter= str.erase(iter) ;"is a good custom.But i puzzle that use a vector<int>::it erator like
      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)

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by evenstar
        I know use iterator like "iter= str.erase(iter) ;"is a good custom.But i puzzle that use a vector<int>::it erator 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

        Comment

        • evenstar
          New Member
          • Jul 2009
          • 30

          #5
          I see,and appreciate your help very much.

          Comment

          Working...