Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize unordered_map in the initializer list

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?

like image 917
ilya1725 Avatar asked Jun 19 '17 23:06

ilya1725


People also ask

Is unordered_map initialized with 0?

The value object is value-initialized, not zero-initialized.

How is an unordered_map implemented in C++?

Internally unordered_map is implemented using Hash Table, the key provided to map are hashed into indices of a hash table that is why the performance of data structure depends on hash function a lot but on an average, the cost of search, insert and delete from the hash table is O(1).

How do you clear an unordered map in C++?

unordered_map::clear() function is used to remove all elements from the container. When this function is applied to unordered_map its size becomes zero. Return type: This function return nothing.


Video Answer


1 Answers

Use braces instead of the parentheses

class test {
 public:
    test()
      : map_{{23, 1345}, {43, -8745}} {}

 private:
   const std::unordered_map<long, long> map_;
 };
like image 169
Vlad from Moscow Avatar answered Oct 13 '22 20:10

Vlad from Moscow