0

I want to add a std::map m_mapName in the initialization list of the constructor.

If I type m_mapName() in the constructor's init list, the compiler accepts it.

But, is it correct? If it is not correct, how can I add the map to the initialization list?

Then, I do several insertions in the map. What is a more elegant way of inserting values, so I don't call insert function everytime?


More info:

Just like in : C++, can I statically initialize a std::map at compile time?, the compiler doesn't accept syntax like:

std::map<int, char> example = { (1,'a'),
                            (2, 'b'),
                            (3, 'c') };

Cannot use Boost. My code looks like this:

* className.h: *

typedef std::map <uint16_t, int> mapType;

typedef std::pair <uint16_t, int> mapPair;

className{

private: 

    mapType m_mapName; 

}

* className.cpp: *

className::className () : 

m_mapName()

{

...

m_mapName.insert(mapPair(someMapValue1, 0));

m_mapName.insert(mapPair(someMapValue2, 0));

m_mapName.insert(mapPair(someMapValue3, 0));
Community
  • 1
  • 1
Developer
  • 11
  • 2

1 Answers1

0

Yes, your code is correct. And the linked question shows what to initialize it with

className::className () 
:m_mapName{ 
    {someMapValue1, 0}, 
    {someMapValue2, 0}, 
    {someMapValue3, 0}}
{}
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
  • The approach above gives me: no matching function for call to 'std::map, std::allocator > >::map()' – Developer Dec 13 '14 at 01:41
  • Changed the type from 'uint16_t' to 'int'. The code looks like: className::className () :m_mapName{ {0, 0}} {} Unfortunately, I get _expected '{' before 'm_mapName'_ and _expected constructor, destructor, or type conversion before '{' token_ – Developer Dec 13 '14 at 01:46
  • I guess my code the way it is works because somehow m_mapName() calls some default constructor. But I am not sure – Developer Dec 13 '14 at 02:01
  • Also, I can't reproduce your issue: http://coliru.stacked-crooked.com/a/2cccca1a328c81c7 – Mooing Duck Dec 14 '14 at 18:56