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?
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?
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.