override-map::直接与lambda函数进行比较
override map::compare with lambda function directly
尝试使用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;
}
}
相关文章:
- C++自定义比较函数
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 为什么 std::stable_sort() 的比较函数的参数必须是设置常量?
- 如何定义集合数组的比较函数?
- 根据比较函数C++对数组进行排序
- 使用自定义比较函数在类内进行列表排序
- 如何更改 std::set 的比较函数?
- 使用类似的比较函数时,在 c++ 中为 std:sort 获得不同的结果
- std::映射服装比较函数和函数/lambda错误
- 在C++排序中为比较函数指定参数
- 使用右值的比较函数
- 为什么比较函数类型需要指定为模板参数?
- 我应该将 lambda 或函子用于比较函数吗?
- 比较函数模板中的 VARTYPE 和 typeid().name / typename
- 如何键入定义一个专门的 std::set 模板,使用特定的比较函数实例化
- 无法在 std::sort 中使用 cdef 函数作为比较函数
- 关联容器,比较函数不是元素类型的一部分吗?
- 标准::lower_bound的比较函数
- 关于如何在 std::sort 和 std::p riority_queue 中使用自定义比较函数的困惑