Segmentation fault with vectors and iterators?

I am working on very large code.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
void ADe::aNe(int v, set<int> &nei)
    {
        for(set<int>::iterator iter = vert2tri[v].begin(); iter != vert2tri[v].end(); iter++)
        {
            int tri = *iter;
            if(triann[tri].a != v)
            {
                nei.insert(triann[tri].a);
            }
        }
    }


This is the biggest issue right here- once you use something like emplace or insert, you invalidate the iterator. In other words, the moment you call nei.insert, your code will go kaput the next run through the for loop.
If you want to keep it like that anyway, that form of insert returns a std::pair<iterator, bool>. The bool can be used to test if the insertion succeeded, and the iterator returned is either an iterator of the newly inserted element or where the element already existed in the set. Basically, you can rewrite that section to do the following:
6
7
8
9
10
11
12
13
if (triann[tri].a != v)
{
    // normally I would use 'auto' here, but I'm unsure of whether you are
    // using C++11 or not so I'll assume you aren't.
    std::pair<std::set<int>::iterator, bool> ret = nei.insert(triann[tri].a);
    if (ret.second)
        iter = ret.first;
}


EDIT:
Actually, this probably won't work anyway... there's nothing that says it will be inserted after the current element in the iteration. You'll have to think of another way.
Last edited on
This is the biggest issue right here- once you use something like emplace or insert, you invalidate the iterator.

The iterator is not for the container that is being inserted into. Even if it were, insertions do not invalidate iterators for sets. This doesn't seem likely to be the problem to me.
This is the biggest issue right here- once you use something like emplace or insert, you invalidate the iterator. In other words, the moment you call nei.insert, your code will go kaput the next run through the for loop.


So how should I resolve the issue?
Topic archived. No new replies allowed.