简体   繁体   中英

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:

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM