std::<int>betterer() 比较器与 partial_copy_sort 的困难,在 Mac OSX 上"no matching function call.."

Difficulties with std::greater<int>() comparator with partial_copy_sort, "no matching function call.." on Mac OSX

本文关键字:Mac OSX no call function matching copy betterer gt int lt      更新时间:2023-10-16

目前正在使用一些老C++,但是在使用greater<int>()比较器查找映射中具有最大值的前k个键时遇到了一些麻烦。

编译接收错误时:

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:5138:17: error: no matching function for call to object of type 'std::__1::greater<int>'
        if (__comp(*__first, *__result_first))
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/algorithm:5160:12: note: in instantiation of function template specialization 'std::__1::__partial_sort_copy<std::__1::greater<int> &, std::__1::__hash_map_iterator<std::__1::__hash_iterator<std::__1::__hash_node<std::__1::__hash_value_type<std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >, int>, void *> *> >, std::__1::__wrap_iter<std::__1::pair<std::__1::vector<std::__1::basic_string<char>, std::__1::allocator<std::__1::basic_string<char> > >, int> *> >' requested here
        return __partial_sort_copy<_Comp_ref>(__first, __last, __result_first, __result_last, __comp);
       ^

哎呀,好丑...以下是一些上下文:

上下文

我有一个unordered_map<vector<string>,int>>结构,我正在尝试在我的地图中找到具有最大int值的前 k 个字符串。

#include <string>
#include <unordered_map>
#include <algorithm>
#include <functional>
#include <vector>
//...
unordered_map<vector<string>, int> database;
vector<pair <vector<string>, int> > top_k(3);
partial_sort_copy(my_map.begin(),
                  my_map.end(),
                  top_k.begin(),
                  top_k.end(), 
                  greater<int>());

不是最好的 cpp 程序员,很想听听一些您必须纠正这种情况的建议?

根据 cpp首选项的文档,比较器函数需要一个类型签名,如下所示:

bool cmp(const Type1 &a, const Type2 &b(;

类型类型1

和类型2 必须使得 RandomIt 类型的对象可以取消引用,然后隐式转换为这两个对象。

RandomIt迭代器对应于top_k结构,当取消引用时,该结构的类型为pair <vector<string>, int>,而std::greater<int>具有bool operator()( const int& lhs, const int& rhs )的比较函数。换句话说,这不起作用,因为pair <vector<string>, int>不会转换为int

一种解决方案是提供自己的比较器:

std::partial_sort_copy(my_map.begin(), my_map.end(), top_k.begin(), top_k.end(),
[](const pair<vector<string>, int>& lhs, const pair<vector<string>, int>& rhs) {
    return lhs.second > rhs.second;
});