BitKnight
BitKnight

Reputation: 190

How to declare STL Set with comparison Object of class with parametrized constructor

When using the set, I want to pass my own comparison function which also takes a parameter. How to do that and how to pass that set as reference to other functions?

For example, I've Comparator Class (with operator() overloaded and private default constructor) which takes an argument in constructor which is used while doing comparison. which works fine with sort algorithms like,

sort(myVector.begin(), myVector.end(), Comparator(10));

but how do I declare a set with this comparator object with parameter.

I've tried these syntax's,

std::set< MyObj, bool(*)(const MyObj&, const MyObj&)>   myObjSet(Compatrator(100));

Now when I insert as, myObjSet.insert(MyObj(0)), it gives error as Error: "left of '.insert' must have class/struct/union"

Now when I declare set as,

std::set< MyObj, Comparator(int)> myObjSet;

it gives error as "function returning function".


class Comparator
{
    int m_cmpParameter;
    Comparator();

public:

    ~Comparator();
    Comparator(int pCmpParam):m_cmpParameter(pCmpParam){}

    bool operator()(const MyObj& pObjA, const MyObj& pObjB);
};

In my project I've this one class for all comparisons required by STL containers. How do I use this Comparator class with Set with passing a parameter to comparison object? And How do I pass this set as reference to other functions, more specifically, what should be the function signature?

Thank you.

Upvotes: 2

Views: 582

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154015

If you need a parameter in your comparator, you'll need to use a function object. Something along the lines of your class. I think you'll need to make the function call operator a const member. You'd use it something like this:

std::set<MyObj, Comparator> myObjSet(Comparator(100));

Upvotes: 6

Related Questions