map<int,int> a;
... put stuff in a ...
int loc=foo(some,data);
for(int i=0; i<a[loc]; ++i)
{
...do some stuff..
}
for(map<int,int>::iterator it=a.begin(); it!=a.end(); ++it)
{
... do some other stuff ...
}
The above code has at least one(!) big potential bug in it:
If the value of
loc
is not one of the values already stored in a
, then the map will create an entry automatically using the default constructor for the value type (a zero in the case of integers). This is potentially disastrous for the loop that iterates over the map. It's also annoying to try to find when debugging!A safer method would be to use
map::find
to return an iterator to the element you want or map::end
if it doesn't exist. So much for syntactic sugar! A straight replacement for the code is too ugly for my taste, but I found a reasonable workaround using std::copy
.