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

C++ erase from set of pointers does not work?

I created a set of pointers, and tried to erase one member in the following code:

#include <iostream>
#include <set>

using namespace std;

struct Node{
    Node(int val){
        this->val = val;
    }
    int val;
    Node* prev;
    Node* next;
};

struct comp{
    bool operator()(const Node* a, const Node* b) const{
        return a->val<=b->val;
    }
};

int main() {
    set<Node*, comp> s;
    Node* n1 = new Node(1);
    s.insert(n1);
    Node* n2 = new Node(2);
    s.insert(n2);
    Node* n3 = new Node(1);
    s.insert(n3);
    
    for(auto it=s.begin();it!=s.end();it++){
        cout<<(*it)->val<<",";
    }
    cout<<endl;

//print out 1, 1, 2
    
    s.erase(n1);
    
    for(auto it=s.begin();it!=s.end();it++){
        cout<<(*it)->val<<",";
    }
    cout<<endl;

//still print out 1, 1, 2 after deleting n1

    return 0;
}

It seems that after erasing the pointer, the printing result still shows it. Can someone help me explain this? If I want to erase the pointer from the set, what is the proper way to do it?

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

>Solution :

Your comp functor does not meet the [Compare][1] requirement

struct comp{
    bool operator()(const Node* a, const Node* b) const{
        a->val<=b->val;
    }
};

Compare is a set of requirements expected by some of the standard
library facilities from the user-provided function object types.

The return value of the function call operation applied to an object
of a type satisfying Compare, when contextually converted to bool,
yields true if the first argument of the call appears before the
second in the strict weak ordering relation induced by this type, and
false otherwise.

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