CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: STL Problem

  1. #1
    Join Date
    May 2001
    Location
    Kansas City, Missouri
    Posts
    45

    Angry STL Problem

    Can anyone tell me why example A works and example B throws an exception?

    vTempContents is a vector<string>. m_strItr is an iterator. m_strMarker is a string. m_fGlossOut is an ofstream object.

    Example A

    m_strItr = vTempContents.begin();
    while (m_strItr != vTempContents.end()) {
    if(m_strItr != m_strMarker) {
    m_fGlossOut.write(m_strItr->c_str(), m_strItr->size());
    }
    m_strItr++;
    }

    Example B

    m_strItr = vTempContents.begin();
    while (m_strItr != m_strMarker) {
    if (m_strItr != vTempContents.end()) {
    m_fGlossOut.write(m_strItr->c_str(), m_strItr->size());
    }
    m_strItr++;
    }

    Thanks in advance.

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725
    Maybe I am missing something, but how does the lines :

    Code:
    if(m_strItr != m_strMarker) { 
    
    //
    // ...
    //
    
    while (m_strItr != m_strMarker) {
    even compile ?

    if m_strIter is an iterator and m_strMarker is a string ?

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449
    Example A shouldn't have worked (or compiled). It should be:
    Code:
    if ( *m_strItr != m_strMarker )
    // NOT if (m_strItr != m_strMarker )
    You can't compare an iterator to a string. An iterator must be dereferenced before using the object.

    Anyway, if you just made a mistake and forgot to post the "*", then the probable reason why 'B' crashes is that you will eventually compare a string to the end() iterator . Never dereference the end() iterator! The end() iterator points one past the valid sequence of elements. If you try to access what end() is pointing to, look out for trouble.
    Code:
    while (*m_strItr != m_strMarker) // BOOM!!  m_strIter may be pointing to end()!!  Illegal access!!
    {
       if (m_strItr != vTempContents.end())      
       {
            //...
       }
       m_strItr++; // m_strIter may have been incremented to the end().
    }
    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; June 7th, 2002 at 02:55 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured