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

标签 c++ sorting

目前正在使用一些旧的 C++,但在使用 greater<int>() 时遇到了一些麻烦用于在映射中查找具有最大值的 top 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);
       ^

Yikes that's ugly...这里有一些背景:

上下文

我有一个 unordered_map<vector<string>,int>>我试图在我的 map 中找到最大的 k 字符串的构造 int值(value)。

#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 程序员,想听听您对这种情况的补救建议吗?

最佳答案

根据 cppreference 的文档,比较器函数需要这样的类型签名:

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

The types Type1 and Type2 must be such that an object of type RandomIt can be dereferenced and then implicitly converted to both of them. ​

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;
});

关于c++ - std::greater<int>() 与 partial_copy_sort 比较器的困难,Mac OSX 上的 "no matching function call..",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49834979/

相关文章:

c++ - 使用快速排序观察二次行为 - O(n^2)

c++ - 正则表达式:在开头以外的任何地方接受空格

C++ 除了使用 tbb::task_group 之外,如何同时运行三个不同的 parallel_for 函数?

c++ - 用作模板函数输入的函数的 void 返回值被视为参数

string - 在 MATLAB 中对字符串进行排序,如 Windows 7 在资源管理器中对文件名进行排序(尊重数字中间字符串)

mysql - 根据用户模型的数组属性中的值对 Rails 中的用户进行排序

C++ 重新定义 - 头文件

c++ - 为什么保守函数允许未定义的行为?

java - 从 "slow"和 "head"之间的排序链表关系中删除重复项

python - 查找数组是否可以转换为严格递增顺序