Given class C
, and function int f(C c)
, what is the proper idiom to create a std::priority_queue<C>
which uses the standard <
comparitor, not over C
but over f(C)
?
Asked
Active
Viewed 256 times
0

SRobertJames
- 8,210
- 14
- 60
- 107
-
Write a predicate for use with the priority queue template, i.e. do *not* use operator `<` or the equivalent `std::less` in the queue. For implementing that predicate, you can of course use those. Note that this means you can *not* use `priority_queue
` but that you will have to specify the third template parameter (and thus also the second), too. – Ulrich Eckhardt Apr 12 '15 at 09:10 -
@UlrichEckhardt Does that require making a functor object? How else can I put the predicate into the template param? – SRobertJames Apr 12 '15 at 09:36
-
Not an object but a type. You can also provide a function pointer, which is probably the easiest way to do it. You should be able to find examples for that if you look for examples involving the class templates `set` and `map` or the algorithms `find_if` and `sort`. – Ulrich Eckhardt Apr 12 '15 at 10:10
1 Answers
0
Refer 1
``// binary predicate function
bool Compare1(C item1, C item2){
return f(item1) > f(item2);
}`
//`binary predicate functor
class Compare2
{
public:
bool operator() (C item1, C item2)
{
return f(item1) > f(item2);
}
};
int main()
{
std::priority_queue<C, std::vector<C>, std::function<bool(C, C)>> pq1(Compare1);
std::priority_queue<C, std::vector<C>, Compare2> pq2;
return 0;
}