是否可以 return 具有自定义排序功能的关联容器?
Is it possible to return an associative container with a custom sort function?
在我的一个项目中,我必须 return 一个带有来自函数的自定义排序函数的映射,但是我不知道我应该如何指定 return -所述功能的类型。
下面是一个简化的例子:
#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;
}
在我的一个项目中,我必须 return 一个带有来自函数的自定义排序函数的映射,但是我不知道我应该如何指定 return -所述功能的类型。
下面是一个简化的例子:
#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;
}