jeudi 13 décembre 2018

How to use priority_queue with a non-static method of class instance?

Suppose I have a simple class like this:

class Test {
public:
  Test(int reference) { m_reference = reference; }
  void feed(int x) { m_data.push_back(x); }
  int get() { return m_data.front(); }
private:
  int m_reference;
  std::vector<int> m_data;
};

Instead of a std::vector, I would like to feed values into a std::priority_queue. Instead of returning the .front() value, I would like to .get() the .top() value of the priority_queue based on a custom compare function. Let's say this custom comparison is computed as the absolute difference between a value and the instance reference.

I have no idea how to declare the std::priority_queue in my class attributes.

I have tried:

bool compare(int a, int b) {
    return std::abs(a - m_reference) < std::abs(b - m_reference);
}

And then:

std::priority_queue<int, std::vector<int>, decltype(&Test::compare)> m_priority;

But this won't work (see Repl.it).

Any idea how to solve this please?

Aucun commentaire:

Enregistrer un commentaire