3

I have created a vector of sets in my program, and I need to go through each of the sets. In case a specific element is found in the set, I need to add a new set to the vector. However, this gives me a segmentation fault as soon as my array's counter reaches the elements that I inserted later (within the loop). In the following code, switching on list.push_back(cS) gives me a segmentation fault.

int main(void)  {
set<int> cS;
vector<set<int> > list;

cS.insert(1);
list.push_back(cS);

cS.insert(2);
list.push_back(cS);

for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        if (*itr == 1 || *itr == 2)
        {
            cS.clear();
            cS.insert(3);
            //list.push_back(cS);
        }
    }
}

for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        cout << *itr << endl;
    }
}

return 0;
}

I would be grateful if someone could explain why this gives an error (in gcc).

Thank you for going through my post.

2
  • Just out of curiosity, why do you use iterators for the set but not the vector? Mar 23, 2012 at 7:41
  • Out of habit, I guess. As far as I know, for a vector, using an iterator or an index are equivalent.
    – Arani
    Mar 23, 2012 at 16:13

1 Answer 1

6

When you push_back into your vector you invalidate all references to elements in it in the case the vector needs to allocate more memory. In your case the iterator itr becomes invalid after the push_back. One solution would be to add the sets to a separate list (vector) and then append them all at once after the for loop:

vector<set<int> > add;
for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        if (*itr == 1 || *itr == 2)
        {
            cS.clear();
            cS.insert(3);
            add.push_back(cS);
        }
    }
}
list.insert(list.end(), add.begin(), add.end());
8
  • In that case, is there no way to iterate through each element of the vector, while in special cases inserting some elements to it?
    – Arani
    Mar 23, 2012 at 7:41
  • push_back doesn't necessarily invalidate iterators, some call to push_back might invalidate. Mar 23, 2012 at 7:43
  • @user571376: use index-based iteration. Mar 23, 2012 at 7:43
  • The exact rules here are covered in an FAQ post: stackoverflow.com/questions/6438086/iterator-invalidation-rules
    – je4d
    Mar 23, 2012 at 7:44
  • 1
    @Nawaz Correct, but the only way to code is to assume it does. Mar 23, 2012 at 7:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.