beginner-level problem... I think...

Jun 6, 2013 at 4:01pm
This has worked in the past...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//eliminate the child from the list
    map<string, int> newpar = parents;
    string chil = child;
    for(map<string, int>::iterator it = newpar.begin(); it != newpar.end();)
    {
        
        //(it == newpar.end()) ALWAYS equals false.  This is the problem!!
        
        if(it->first == chil)  //this is where it stops
        {
            //(it == newpar.end()) is false here... always...
            newpar.erase(it);
            //loop back without adding the next one
            
            //(it == newpar.end()) is false here... always...
            continue;
        }
        
        //only add if we didn't erase anything
        //(it == newpar.end()) is false here... always...
        
        /* WTF...WTFWTFWTFWTF?!?!?!?!*/
        it++;
    }


Will someone help me? I can not figure out why it is throwing segfaults.

Explanation (reason of emplimentation):

The following is supposed to allow for quick search of a parent path. Since the child path is also included within the list, it must be eliminated before we start searching.
Last edited on Jun 6, 2013 at 4:02pm
Jun 6, 2013 at 4:14pm
When you erase an element from a map it invalidates the current iterator (it++ will yield meaningless results.) map::erase returns an iterator pointing to the element that follows the last removed element.
this should fix your problem:
 
it = newpar.erase(it);
Jun 6, 2013 at 4:17pm
My understanding is that a vector<string>::iterator would be able to function correctly in this loop. Is this strictly a map<class, class>::iterator feature?
Jun 6, 2013 at 4:18pm
No. .erase will always invalidate the current iterator (it deletes it!)
Jun 6, 2013 at 4:22pm
@firedraco

Yes, but the the rest take it's place. This loop has worked with vectors flawlessly in the past. This is the first instance where it has not worked.
Jun 6, 2013 at 4:27pm
Yes, but the the rest take it's place.


No, they don't.

You need to stop thinking of iterators as pointers; they are not.

The only reason it worked with vectors is because you got lucky.
Topic archived. No new replies allowed.