c++ - 是否可以返回具有自定义排序功能的关联容器?
问题描述
在我的一个项目中,我必须从一个函数返回一个带有自定义排序函数的地图,但是我不知道我应该如何指定所述函数的返回类型。
一个简化的例子如下:
#include <iostream>
#include <map>
std::map<std::string, bool> get_entries()
{
auto cmp = [](const std::string& a, const std::string& b)
{ return (a.length() != b.length()? a.length() > b.length(): a < b); };
std::map<std::string, bool, decltype(cmp)> entries;
entries.insert({"Mom", true});
entries.insert({"Dad", false});
entries.insert({"Sister", true});
entries.insert({"Brother", true});
entries.insert({"Child", false});
return entries;
}
int main()
{
std::map<std::string, bool> entries(get_entries());
for (auto& [key, value]: entries)
std::cout << "Key: " << key << ", value: " << (value? "true": "false") << std::endl;
return 0;
}
此代码无法编译,因为我需要指定有关 lambda 函数的内容。
这可能吗,我该怎么做?
先感谢您。
解决方案
是的:停止使用这样的 lambda。使您的自定义排序函数成为实际类型,因为它是您界面的一个明确部分:
struct custom_sort
{
bool operator() const (const std::string& a, const std::string& b)
{
return (a.length() != b.length()? a.length() > b.length(): a < b);
};
};
std::map<std::string, bool, custom_sort> get_entries()
{
std::map<std::string, bool, custom_sort> entries;
entries.insert({"Mom", true});
entries.insert({"Dad", false});
entries.insert({"Sister", true});
entries.insert({"Brother", true});
entries.insert({"Child", false});
return entries;
}
推荐阅读
- zpl - ZPL 字符串方尖碑
- python - 使用子进程在 Shell/Python 中获取字符串
- amazon-web-services - SQS 或 Kinesis 哪个更适合排队?
- assembly - 汇编语言当前位置指针
- ruby - Paw:可以用目标语言从哈希/字典源复制/粘贴数据吗?
- jquery - Python requests_html 通过使用 JQuery 单击按钮来提交表单
- c# - 使用会话变量在一页上选择一个日期,并在 C# 中离开页面后保持相同的日期
- jquery - jQuery fn 到 npm 包
- dynamics-crm - CRM Dynamics 快速创建表单标签
- php - 数组错误可能是 PHP 版本问题吗?