【发布时间】:2013-05-26 19:54:07
【问题描述】:
我在查看 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 似乎与函子有很大的不同,以至于它不是一个常量表达式。对吗?
【问题讨论】:
-
std::hash专门用于std::string,如果您不想改进/更改哈希,则无需自己提供一些东西。另外,想想你在做什么:std::unordered_map期望一个 type 作为模板参数,而 lambda 表达式正是这样 - 一个表达式,即一个值,not i> 一种类型。 -
我发现在我使用的g++编译器中(v4.5.3 with -std=gnu++0x),如果我在使用字符串键。
-
至于它是一个表达式,是的,我想这就是答案。
-
4.5.3 对 C++11 的支持很少。不要将此组合用于任何严重的事情。