Search code examples
c++pointersstdstdset

Using std::less for a set of pointers


I've a some class where I'm declaring a set like this:

std::set<UPFIR::RetentionSignal*> _retSignalSet; 

I'm trying to use std::less compare function on it. I tried something like this:

std::set<UPFIR::RetentionSignal*, std::less<UPFIR::RetentionSignal*>> _retSignalSet; 

The feedback I'm getting is "adding std::less wont make it determinism. You have to compare the name", Can somebody explain me how can this be accomplished as I haven't worked with std::less before?

Thanks


Solution

  • If the requirement is that the set should be sorted by name, then std::less does not help. You must provide a custom comparator that compares the name. For example (just an untested sketch):

    struct LessByName {
        bool operator<(UPFIR::RetentionSignal* a, UPFIR::RetentionSignal* b)
        {
            return a->name < b->name;
        }
    };
    

    and then use it like

    std::set<UPFIR::RetentionSignal*, LessByName> _retSignalSet;
    

    BTW, the comment "std::less won't make it deterministic" is wrong, because std::less is defined to provide a total order on pointers. The order you get may just not be the one required to fulfill your task.