Reputation: 9743
I can use an initializer list to initialize a std::map
as follows:
std::map<int, int> m {{5, 6}, {3, 4}, {1, 2}};
I can change the ordering of a std::map
by providing a comparison lambda (see here, search for "lambda") as follows:
auto comp = [](int a, int b) { return b < a; };
std::map<int, int, decltype(comp)> m(comp);
Now, I tried to do both at the same time as follows:
std::map<int, int, decltype(comp)> m(comp) {{5, 6}, {3, 4}, {1, 2}};
However, this does not compile. On VS 2013 I'm getting the following error:
error C2448: 'm' : function-style initializer appears to be a function definition
I also tried running the code on Ideone, but there I'm getting the following error:
error: expected ‘}’ at end of input
This looks like some kind of most vexing parse to me. I tried to provide an assignment operator or use std::make_pair
within the initializer list, but to no avail.
How can I use an initializer list here? Is it possible at all?
Upvotes: 3
Views: 978
Reputation: 20918
The constructor which takes an initializer list and a comparator is the following:
map( std::initializer_list<value_type> init,
const Compare& comp = Compare(),
const Allocator& alloc = Allocator() );
So you should write:
auto comp = [](int a, int b) { return b < a; };
std::map<int, int, decltype(comp)> m{{{5, 6}, {3, 4}, {1, 2}}, comp};
Upvotes: 3