问题描述
我有一个 vector
的 priority_queue
s是 string
s:
I have a vector
of priority_queue
s of string
s:
vector<priority_queue<string>>> queues(VECTOR_CAPACITY);
问题是我如何将自定义 string
比较器应用于那些 priority_queue
s?
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.
我尝试过这种方式:
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)')
比较器将较短的字符串放在较长的字符串之前,并且当它们相等的长度时,使用标准的字典比较方法如下:
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;
};
推荐答案
您还需要将您的lambda实例传递给 std :: priority_queue
,如说:
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));
不幸的是,复制列表初始化即 {comparator}
在这里不起作用,因为第二个构造函数重载由于某种原因被标记为 explicit
.
Unfortunately, copy-list-initialization i.e. {comparator}
doesn't work here, because the 2nd constructor overload is marked explicit
for some reason.
这篇关于具有自定义字符串比较器的字符串的priority_queue的C ++向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!