-
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.
-
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 ?
-
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