带有自定义字符串比较器的字符串的priority_queue的C++向量

C++ vector of priority_queue of strings with custom strings comparator

本文关键字:字符串 queue C++ 向量 自定义 比较器 priority      更新时间:2023-10-16

我有一个vectorpriority_queue s的string s:

vector<priority_queue<string>>> queues(VECTOR_CAPACITY);

问题是如何将自定义的string比较器应用于这些priority_queue

如果这是相关的,我想要的比较器将较短的字符串放在较长的字符串之前,当它们的长度相等时,使用标准字符串比较。

我试过这种方法:

auto comparator = [] (string s1, string s2) { return s1.length() < s2.length() || s1 < s2; };
vector<priority_queue<string, vector<string>, decltype(comparator)>> queues(VECTOR_CAPACITY);

但它编译时没有出现以下错误:

No matching constructor for initialization of 'value_compare' (aka
'(lambda at Example.cpp:202:23)')

编辑:比较器将较短的字符串放在较长的字符串之前,当它们相等时,使用标准的字典比较,如下所示:

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,因为这个Q&A说:

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


我把VECTOR_CAPACITY改成了VECTOR_SIZE,因为这就是参数的含义