如何使用初始化列表初始化带有比较 lambda 的 std::map?
How can I initialize a std::map with comparison lambda by using an initializer list?
我可以使用初始化列表来初始化 std::map
,如下所示:
std::map<int, int> m {{5, 6}, {3, 4}, {1, 2}};
我可以通过提供比较 lambda(参见 here,搜索 "lambda")来更改 std::map
的顺序,如下所示:
auto comp = [](int a, int b) { return b < a; };
std::map<int, int, decltype(comp)> m(comp);
现在,我尝试同时执行以下操作:
std::map<int, int, decltype(comp)> m(comp) {{5, 6}, {3, 4}, {1, 2}};
但是,这不会编译。在 VS 2013 上,我收到以下错误:
error C2448: 'm' : function-style initializer appears to be a function definition
I also tried running the code on Ideone,但出现以下错误:
error: expected ‘}’ at end of input
这看起来像某种 most vexing parse to me. I tried to provide an or use std::make_pair
within the initializer list,但无济于事。
我如何在这里使用初始化列表?有可能吗?
采用初始化列表和比较器的构造函数如下:
map( std::initializer_list<value_type> init,
const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
所以你应该写:
auto comp = [](int a, int b) { return b < a; };
std::map<int, int, decltype(comp)> m{{{5, 6}, {3, 4}, {1, 2}}, comp};
我可以使用初始化列表来初始化 std::map
,如下所示:
std::map<int, int> m {{5, 6}, {3, 4}, {1, 2}};
我可以通过提供比较 lambda(参见 here,搜索 "lambda")来更改 std::map
的顺序,如下所示:
auto comp = [](int a, int b) { return b < a; };
std::map<int, int, decltype(comp)> m(comp);
现在,我尝试同时执行以下操作:
std::map<int, int, decltype(comp)> m(comp) {{5, 6}, {3, 4}, {1, 2}};
但是,这不会编译。在 VS 2013 上,我收到以下错误:
error C2448: 'm' : function-style initializer appears to be a function definition
I also tried running the code on Ideone,但出现以下错误:
error: expected ‘}’ at end of input
这看起来像某种 most vexing parse to me. I tried to provide an std::make_pair
within the initializer list,但无济于事。
我如何在这里使用初始化列表?有可能吗?
采用初始化列表和比较器的构造函数如下:
map( std::initializer_list<value_type> init,
const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
所以你应该写:
auto comp = [](int a, int b) { return b < a; };
std::map<int, int, decltype(comp)> m{{{5, 6}, {3, 4}, {1, 2}}, comp};