Given a std::map<key_type, value_type>
, a lookup for an arbitrary key through operator [](cont key_type&)
will auto-insert value_type()
for said-key if it wasn't present. In your case, value_type
is int
, and int()
is zero-initialized, therefore zero is the result.
if you want to use a different default construct, you have options, the most extreme of which would be writing a custom allocator specialized for int
and a construct
member to us -1 for int
value types (yuck). I think you may find it easier to simply:
std::map <int, int> x;
// load map with values...
int res = -1;
auto it = x.find(31233);
if (it != x.end())
res = x.second;
// use res here.