【问题标题】:Is it possible to return an associative container with a custom sort function?是否可以返回具有自定义排序功能的关联容器?
【发布时间】:2021-05-30 09:23:38
【问题描述】:

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

一个简化的例子如下:

#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 函数的内容。” 确切的错误消息是什么? Edit您的问题并请添加该信息!
  • auto get_entries(), auto entries{get_entries()};

标签: c++ stl containers c++20


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多