C ++ STL set: compare object with external state

These definitions are inside OuterClass:

struct Compare
{
    bool operator ()(const T&, const T&);
};
typedef set<T, Compare> MySet;

My problem is that the compare operator ()function is state dependent OuterClass. ( MySetInstances are used during the optimization algorithm, and they must be sorted differently at different stages.)

Is there a way / workaround for accessing non-static members OuterClassfrom the compare function operator ()?

+5
source share
1 answer

Is there a way / workaround for accessing non-static OuterClass members from a comparison function () operator?

There is. Just write a custom constructor for Compare, which accepts and stores the link to OuterClass, as follows:

struct Compare
{
    Compare(OuterClass& o) : oc(o) { }
    bool operator ()(const T&, const T&)
    {
        // Uses oc somehow...
    }
private:
    OuterClass& oc;
};

, , - :

int main()
{
    typedef std::set<T, Compare> MySet;

    OuterClass oc; // <== Construct an object of type Outerclass somehow...

    MySet ms(Compare(oc)); // <== Construct your comparator and pass it
                           //     in input to the constructor of std::set
}

: . . 23.2.4/3 ++ 11:

" " , , operator== . k1 k2 , comp, comp(k1, k2) == false && comp(k2, k1) == false. k1 k2 , comp(k1, k2) .

+5

All Articles