首页 > 解决方案 > 是否可以返回具有自定义排序功能的关联容器?

问题描述

在我的一个项目中,我必须从一个函数返回一个带有自定义排序函数的地图,但是我不知道我应该如何指定所述函数的返回类型。

一个简化的例子如下:

#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 函数的内容

这可能吗,我该怎么做?
先感谢您。

标签: c++stlcontainersc++20

解决方案


是的:停止使用这样的 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;
}

推荐阅读