jeudi 3 juin 2021

Storing equal objects in a set

What I'm trying to do: order elements in the set by elem->value, but still recognize that they're distinct elements based on the memory address they're pointing to.

#include <iostream>
#include <set>

using namespace std;

struct Node {
    int value;
    
    Node(int v) : value(v) {}
};

int main()
{
    Node* a = new Node(10);
    Node* b = new Node(10);
    Node* c = new Node(20);

    if (a == b) {
        cout << "a == b" << endl;
    }
    
    if (a == c) {
        cout << "a == c" << endl;
    }
    
    auto comparator = [](Node* lhs, Node* rhs) {
        return lhs->value < rhs->value;
    };

    set<Node*, decltype(comparator)> s(comparator);
    s.insert(a);
    s.insert(b);
    s.insert(c);
    
    cout << "after inserts, s.size() = " << s.size() << endl;
    
    s.erase(a);
    
    cout << "after erase, s.size() = " << s.size() << endl;
    
    delete(a);
    delete(b);
    delete(c);

    return 0;
}

Since a != b, I expect to get:

after inserts, s.size() = 3
after erase, s.size() = 2

But instead, I get:

after inserts, s.size() = 2
after erase, s.size() = 1

With lhs->value <= rhs->value, I get:

after inserts, s.size() = 3
after erase, s.size() = 3

With multiset, I get:

after inserts, s.size() = 3
after erase, s.size() = 1

Aucun commentaire:

Enregistrer un commentaire