override-map::直接与lambda函数进行比较

override map::compare with lambda function directly

本文关键字:比较 函数 override-map lambda      更新时间:2023-10-16

尝试使用lambda覆盖map::compare函数,似乎以下解决方案有效。

auto cmp = [](const int&a, const int& b) { return a < b; };
std::map<int, int, decltype(cmp)> myMap(cmp);

但是,我必须先定义cmp,然后再使用它
我可以在不定义"cmp"的情况下执行此操作吗?

否,您不能在未赋值的上下文中使用lambda,即您的示例中的模板参数。因此,您必须在其他地方定义它(使用auto),然后使用decltype。。。另一种方法,正如前面提到的,是使用"序数"函子

如果您的问题是"如何在定义映射时使用lambda表达式*一次*",您可以使用lambda到std::function的隐式转换,如下所示:

#include <iostream>
#include <functional>
#include <map>
int main()
{
    auto m = std::map<int, int, std::function<bool(const int&, const int&)>>{
        [](const int& a, const int& b)
        {
            return a < b;
        }
    };
    return 0;
}

您可以为map类型引入一个别名,以减少以后的键入。。。

#include <iostream>
#include <functional>
#include <map>
#include <typeinfo>
typedef std::map< int, int, std::function<bool(const int&, const int&)> > MyMap;
int main()
{
    auto cmp = [](const int& a, const int& b) { return a < b; };
    MyMap map(cmp);
    return 0;
}

使用std::function为比较器类型提供适当的类型签名,您可以定义映射类型,然后分配您想要的任何lambda比较。

您可以执行类似的操作,其中映射的类型是从传递给函数的函数中推导出来的。

#include <map>
template<class Key, class Value, class F>
std::map<Key, Value, F> make_map(const F& f) {
    return std::map<Key, Value, F>{f};
}
int main() {
    auto my_map = make_map<int, int>([](const int&a, const int& b) { return a < b; });
    my_map[10] = 20;
}

我看不出有什么理由这么做,但我不会说这没用。一般来说,您需要一个已知的比较器,以便可以轻松地传递地图。通过以上设置,您可以一直使用模板功能,如以下

tempalte<class F>
void do_somthing(const std::map<int, int, F>& m) {
}

这并不一定是坏事,但我的直觉告诉我,拥有一个只能由泛型函数处理的类型是坏事。我认为这对lambda函数来说很好,但仅此而已。这里的解决方案是使用std::function

#include <map>
#include <functional>
template<class Key, class Value>
using my_map_t = std::map<Key, Value, std::function<bool(const Key&, const Key&)>>;
int main() {
    my_map_t<int,  int> my_map{[](const int&a, const int& b) { return a < b; }};
    my_map[10] = 20;
}

现在,您可以使用任何您想要的谓词,并且有一个具体的类型可以使用,my_map

希望这能有所帮助!

在C++20中,您可以执行以下操作:

std::map<int, int, decltype([](const int&a, const int& b) { return a < b; })> myMap;

int main() {
    myMap.insert({7, 1});
    myMap.insert({46, 2});
    myMap.insert({56, 3});
    for (const auto& [key,value]:myMap) {
        std::cout <<  key <<  "  " << value << std::endl;
    }
}