初始化初始化列表中的unordered_map(Initialize unordered_map in the initializer list)

我正试图找到一个可能是一个非常微不足道的问题的解决方案。 我想在类初始化列表中初始化我的const unordered_map 。 但是,我还没有找到编译器(GCC 6.2.0)将接受的语法。 代码链接在这里 。

#include <unordered_map> class test { public: test() : map_({23, 1345}, {43, -8745}) {} private: const std::unordered_map<long, long> map_; };

错误:

main.cpp: In constructor 'test::test()': main.cpp:6:36: error: no matching function for call to 'std::unordered_map<long int, long int>::unordered_map(<brace-enclosed initializer list>, <brace-enclosed initializer list>)' : map_({23, 1345}, {43, -8745}) {} ^

是否不允许在初始化列表中初始化复杂常量? 或者语法必须不同?

I'm trying to find a solution to what may be a very trivial problem. I would like to initialize my const unordered_map in the class initializer list. However I'm yet to find the syntax that the compiler (GCC 6.2.0) will accept. A code link is here.

#include <unordered_map> class test { public: test() : map_({23, 1345}, {43, -8745}) {} private: const std::unordered_map<long, long> map_; };

Error:

main.cpp: In constructor 'test::test()': main.cpp:6:36: error: no matching function for call to 'std::unordered_map<long int, long int>::unordered_map(<brace-enclosed initializer list>, <brace-enclosed initializer list>)' : map_({23, 1345}, {43, -8745}) {} ^

Are the complex constants not allowed to be initialized in the initializer list? Or the syntax has to be different?

最满意答案

使用大括号而不是括号

class test { public: test() : map_{{23, 1345}, {43, -8745}} {} private: const std::unordered_map<long, long> map_; };

Use braces instead of the parentheses

class test { public: test() : map_{{23, 1345}, {43, -8745}} {} private: const std::unordered_map<long, long> map_; };

更多推荐