|
-
June 7th, 2002, 01:43 PM
#1
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.
-
June 7th, 2002, 02:32 PM
#2
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 ?
-
June 7th, 2002, 02:51 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|