c++ - STL priority_queue parameters -
when creating stl priority_queue, third argument (the 1 decides how compare elements in queue decide largest)must class in function operator defined. more convenient if lambda expression supplied. why not allowed? lambda expression should considered compile time constant if not capturing variables, right?
struct compare{ bool operator()(int p, int q){return p > q;} }; priority_queue< int, vector<int>, compare> intpq; priority_queue< int, vector<int>, [](int p, int q){return p > q;} > intpq2;
the second definition, i.e. of intpq2, gives error: template argument 3 invalid. there fundamental problem in accepting second definition, or designers of priority_queue chose not allow it?
the third parameter of std::priority_queue
type. lambda expression not type, rather, expression (you can think of instance or object of something). on top of that, lambdas not have type can known a priori, stateless lambdas convert pointer function .
there work-arounds can use in order instantiate priority_queues lambdas:
make 3rd parameter pointer function , pass stateless lambda constructor. can pass plain function pointers. example,
make 3rd parameter
std::function<bool(int, int)>
, pass kind of lambda matches correct signature constructor. can pass can used constructstd::function<bool(int)>
.
for example,
// no capture. pointer function ok std::priority_queue<int, std::vector<int>, bool (*)(int, int)> q2([](int a, int b){return < b;});
or
// capture. can't use pointer function. std::priority_queue<int, std::vector<int>, std::function<bool(int, int)>> q2([some_var](int a, int b){return < b;});
Comments
Post a Comment