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?

>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.

Leave a Reply