0

When we try to access an object in a map container using a key while that object does not exist, it is automatically constructed using default constructor.

I wonder is there a way to use another constructor, for example, with one parameter?

HanXu
  • 5,507
  • 6
  • 52
  • 76
  • The trivial solution is to wrap the value type, and let `Derived::Derived()` call `Base::Base(param)`. – MSalters Mar 29 '13 at 10:26
  • std::map _value-initializes_ object values using default constructor. So not possible. For references to C++ standards please also see - [link](http://stackoverflow.com/questions/9025792/does-the-default-constructor-of-stdpair-set-basic-types-int-etc-to-zero) – Amar Mar 30 '13 at 03:30

1 Answers1

2

I personally think this behavior is weird, but if you really want to do so, I suggest that explicitly write what you want:

For example:

typedef std::map<int, std::string> MapType;

std::string FindSomething(int key, const std::string& extraParameter)
{
    MapType::iterator It = TheMap.find(key);

    if (It == TheMap.end())
    {
        TheMap.insert(std::make_pair(key, extraparameter));

        return extraParameter;
    }
    else
    {
        return It->second;
    }
}

Do not depend on the automatically insertion.

W.B.
  • 5,445
  • 19
  • 29
Marson Mao
  • 2,935
  • 6
  • 30
  • 45