Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass std::map as a default constructor parameter

I haven't been able to figure this out. It's easy to create two ctors but I wanted to learn if there's an easy way to do this.

How can one pass a std::map as the default parameter to a ctor, e.g.

Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL)

I've tried 0, null, and NULL as VAL, none of the work because they are all of type int, g++ complains. What is the correct default to use here?

Or is this kind of thing not a good idea?

like image 309
recipriversexclusion Avatar asked Nov 08 '10 22:11

recipriversexclusion


People also ask

Does STD map require default constructor?

The default constructor is not required. Certain container class member function signatures specify the default constructor as a default argument. T() must be a well-defined expression ...

Can a default constructor accept parameters?

Default Constructor – A constructor that accepts no parameter is called Default Constructor. It is not necessary to have a constructor block in your class definition. If you don't explicitly write a constructor, the compiler automatically inserts one for you.

What is default map in C++?

By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared.

Is std :: map ordered?

Yes, a std::map<K,V> is ordered based on the key, K , using std::less<K> to compare objects, by default.


1 Answers

Since C++11 you can use aggregate initialization:

void foo(std::map<std::string, std::string> myMap = {});

Example:

#include <iostream>
#include <map>
#include <string>

void foo(std::map<std::string, std::string> myMap = {})
{
    for(auto it = std::cbegin(myMap); it != std::cend(myMap); ++it)
        std::cout << it->first << " : " << it->second << '\n';
}

int main(int, char*[])
{
    const std::map<std::string, std::string> animalKids = {
        { "antelope", "calf" }, { "ant", "antling" },
        { "baboon", "infant" }, { "bear", "cub" },
        { "bee", "larva" }, { "cat", "kitten" }
    };

    foo();
    foo(animalKids);

    return 0;
}

You can play around with this example at Godbolt.

like image 195
Phidelux Avatar answered Oct 14 '22 19:10

Phidelux