问题
I have a vector
of priority_queue
s of string
s:
vector<priority_queue<string>>> queues(VECTOR_CAPACITY);
And the question is how can I apply custom string
comparator to those priority_queue
s?
Should this be relevant, the comparator I want puts shorter strings before longer ones and when they're equal length uses standard strings comparison.
I tried this way:
auto comparator = [] (string s1, string s2) { return s1.length() < s2.length() || s1 < s2; };
vector<priority_queue<string, vector<string>, decltype(comparator)>> queues(VECTOR_CAPACITY);
but it doesn't compile with the following error:
No matching constructor for initialization of 'value_compare' (aka '(lambda at Example.cpp:202:23)')
EDIT: Comparator that puts shorter strings before longer ones and when they're equal length uses standard lexicographic comparison looks like that:
auto comparator = [] (string s1, string s2)
{
if (s1.length() != s2.length())
{
return s1.length() > s2.length();
}
return s1.compare(s2) > 0;
};
回答1:
You also need to pass the instance of your lambda to the std::priority_queue
, as this Q&A says:
using my_queue_t = std::priority_queue<
std::string, std::vector<std::string>, decltype(comparator)>;
std::vector<myqueue_t> queues(VECTOR_SIZE, my_queue_t(comparator));
Unfortunately, copy-list-initialization i.e. {comparator}
doesn't work here, because the 2nd constructor overload is marked explicit
for some reason.
I changed VECTOR_CAPACITY
to VECTOR_SIZE
because that's what the parameter means.
来源:https://stackoverflow.com/questions/36407607/c-vector-of-priority-queue-of-strings-with-custom-strings-comparator