Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Segfault when deleting from a set C++

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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;
}
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading