Assume I have a class in c++:
struct CompareTuple
{
public:
auto operator() (const Tuple& t1, const Tuple& t2) -> bool
{
// do comparison and return
}
};
class Foo
{
public:
// some functions
private:
std::priority_queue<Tuple, std::vector<Tuple>, CompareTuple> heap_;
};
Is this struct CompareTuple
is a proper way in modern C++?
If it is not, what is a proper way to define a custom compare function in priority queue in modern ways?
Because I see, we can use lambda. But I don't know how to define in .h
file together with class Foo
.
I have tried the example I showed above, it works. But I want to know if it's the best way to do in C++20.
You should consider providing the operator<
in the Tuple
itself, which enables the comparison of Tuple
s by default. If this is not intended for the caller side, you can choose either to use functors or lambda functions.
Is this struct
CompareTuple
a proper way in modern C++?
Functors are old but golden tools, which work always everywhere. Therefore, it has still relevance in the modern era (IMO), and nothing to worry about that your code will be outdated if it has been chosen to use.
What is a proper way to define a custom compare function in a priority queue in modern C++? Because I see that we can use lambda [...]
Yes, indeed, you could use lambdas as alternatives. Those are handy tools (Since c++11), by which one could possibly avoid writing arguably lengthy functors, and the definitions of the unnamed function objects (aka. lambda) in place, where it is (possibly only once) required.
For instance, using generic lambdas from c++14, and the support of default constructible lambda in unevaluated context (since c++20), one could do:
class Foo
{
private:
// Using lambda function as a custom comparison
std::priority_queue<Tuple, std::vector<Tuple>,
decltype([](const auto& lhs, const auto& rhs) {
return lhs.mX > rhs.mX; // define the priority as per!
}) > heap;
public:
// .... code
};
Prior to C++20, it requires two steps:
class Foo
{
private:
// Captureless lambda as a custom comparison, stored in a function pointer
bool(*Compare)(const Tuple&, const Tuple&) = [](const Tuple& lhs, const Tuple& rhs){
return lhs.mX > rhs.mX; // define the priority as per!
};
std::priority_queue<Tuple, std::vector<Tuple>, decltype(Compare)> heap{Compare};
public:
// .... code
};