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));
4
  • Did you read the answers on the question you linked to that say exactly how to do this? Commented Dec 13, 2014 at 0:58
  • Yes, I did. The posting doesn't answer my specific question: Why did the compiler accept the way I added the map to the init list and if it is correct? Commented Dec 13, 2014 at 1:13
  • I also cannot use Boost. Commented Dec 13, 2014 at 1:17
  • That's not what your code looks like, you're missing class and a semicolon at least. stackoverflow.com/help/mcve Commented Dec 14, 2014 at 18:55

1 Answer 1

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}}
{}
Sign up to request clarification or add additional context in comments.

4 Comments

The approach above gives me: no matching function for call to 'std::map<short unsigned int, int, std::less<short unsigned int>, std::allocator<std::pair<const short unsigned int, int> > >::map(<brace-enclosed initializer list>)'
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
I guess my code the way it is works because somehow m_mapName() calls some default constructor. But I am not sure
Also, I can't reproduce your issue: coliru.stacked-crooked.com/a/2cccca1a328c81c7

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.