gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:42:58 25 4
gpt4 key购买 nike

目前正在使用一些旧的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com