Home > Net >  Segfault when deleting from a set C
Segfault when deleting from a set C

Time:10-08

Segfaulting code

Hey all, was just wondering how to delete elements from a set if its detected in another set. The current code iterates through both sets using a for loop, then if the value the iterators hold is the same, it attempts to erase from the first set.

It would look something like this:

#include <iostream>
using namespace std;
#include <vector>
#include <string>
#include <set>



int main() {
set<int> myset;
set<int> myset2;

for (int i = 0; i < 10; i  ) {
    myset.insert(i);

}
for (int i = 0; i < 5; i  ) {
    myset2.insert(i);
}

for (auto iter = myset.begin(); iter != myset.end(); iter  ) {
    for (auto iter2 = myset2.begin(); iter2 != myset2.end(); iter2  ) {
        if (*iter == *iter2) {
            myset.erase(*iter);
        }
    }
    
}

for (auto it = myset.begin(); it != myset.end(); it  ) {
    cout << *it;
}
}

CodePudding user response:

The simple solution is to use one for loop.

for (auto val : myset2)
   myset.erase(val);

and not the doubly-nested for loop you're using now.

The std::set::erase can erase by key or iterator. All you need to do is provide the key element in this case.

Full example.

  • Related