我正在查看 std::unordered_map 并看到如果我想使用字符串作为键,我必须创建一个包含仿函数的类。
出于好奇,我想知道是否可以使用 lambda 来代替它。
这是工作原件:
struct hf
{
size_t operator()(string const& key) const
{
return key[0]; // some bogus simplistic hash. :)
}
}
std::unordered_map<string const, int, hf> m = {{ "a", 1 }};
这是我的尝试:
std::unordered_map<string const, int, [](string const& key) ->size_t {return key[0];}> m = {{ "a", 1 }};
失败并出现以下错误:
exec.cpp: In lambda function:
exec.cpp:44:77: error: ‘key’ cannot appear in a constant-expression
exec.cpp:44:82: error: an array reference cannot appear in a constant-expression
exec.cpp: At global scope:
exec.cpp:44:86: error: template argument 3 is invalid
exec.cpp:44:90: error: invalid type in declaration before ‘=’ token
exec.cpp:44:102: error: braces around scalar initializer for type ‘int’
考虑到这些错误,lamba 似乎与函子有足够的不同,以至于它不是一个常量表达式。那是对的吗?