c++ - 隐式转换为 std::sort 但不是 std::map 的比较函数对象(函子)?
问题描述
我一直在使用std::sort
函数作为比较函数。该函数被隐式转换为函子(通过 GCC)。我在声明std::map
类型时尝试了同样的方法,但是失败了。
编译g++ -Wall -Wextra -std=gnu++14 -pedantic
:_
#include <map>
#include <algorithm>
#include <vector>
struct S { int i; };
struct Payload { bool b; };
bool compare(const S* const& lhs, const S* const& rhs)
{
return lhs->i < rhs->i;
}
using MyMap = std::map<const S*, Payload, compare>;
static void foo([[maybe_unused]] const MyMap&) {}
int main()
{
std::vector<const S*> vs;
std::sort(vs.begin(), vs.end(), compare); // OK
MyMap m;
foo(m);
}
这是输出:
main.cpp:13:50: error: type/value mismatch at argument 3 in template parameter list for 'template<class _Key, class _Tp, class _Compare, class _Alloc> class std::map'
13 | using MyMap = std::map<const S*, Payload, compare>;
| ^
main.cpp:13:50: note: expected a type, got 'compare'
有没有一种方法可以将仿函数传递给map
声明,而无需手动定义仿函数类(因为可以使用std::sort
)?
解决方案
您似乎混淆了类型和值。to的第三个参数std::sort
是一个值,to的第三个参数std::map
是一个类型。
using MyMap = std::map<const S*, Payload, bool (*)(const S* const&, const S* const&)>;
完全合法。
然后你可以写
MyMap my_map(compare);
PS在您的排序示例中没有隐式转换为仿函数。作为模板函数,可以使用函数调用运算符合法的任何内容调用 sort。这包括函子和函数指针(除其他外)。
推荐阅读
- postgresql - 如何在“丢失块编号 0”消息后备份/恢复数据库?
- python - Pydantic:JSON 编码的字典键
- r - R将几个数据框导出到不同的Excel文件
- flutter - Flutter:使文本小部件出现在Tap上
- authentication - 在 CakePHP 4.x / Authenticator 2.x 中禁用密码拥有
- javascript - 无法在 MongoDb 中添加数据
- task-parallel-library - 是否有任何库可以对 TPL 数据流块进行诊断?
- flutter - 在颤动中将不同的标记图标添加到我的谷歌地图的几个位置不起作用
- arrays - PostgreSQL fdw 表性能在 5 次完全相同的查询后呈指数下降
- python - 来自 Python 和 Postman 的请求成功,但来自 PHP、Curl 和干净的 Python 容器的请求失败