1

I have my struct:

struct S{ int a; }; 

And i have class:

class Other{ //some fields }; 

I need write functor:

struct Comparator { bool operator()(S& l, S& r) { //some code, considered l,r and any object of class Other } }; 

In operator () should be considered any object of class Other. How to transfer object into functor? I use functor for priority_queue. Object of class Other can't be statical field.

Another ways for this purpose?

1
  • need more information Commented Apr 30, 2015 at 12:23

1 Answer 1

2

Make Comparator store an object of type Other(or reference, shared_ptr or unique_ptr depending on the ownership and validity semantics), and pass this in through Comparator's constructor.

struct Comparator { Comparator(const Other& val) : mVal(val){} bool operator()(S& l, S& r) { //Comparison code here uses l, r and mVal } private: Other mVal; }; 

Create the priority_queue like this, assuming you want to use vector<T> as the underlying container:

Other otherToHelpCompare; Comparator myComparator{otherToHelpCompare}; std::priority_queue<T, std::vector<T>, Comparator> q{myComparator}; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.