Tuesday, August 30, 2011

C++ is hard.


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.

Monday, August 29, 2011

Use Makes Master

Awhile back, I learned to tie my shoes correctly. It turns out that I'd been doing it wrong all these years.

The basic shoe bow is, in some ways, 3/4ths of a Granny Knot or a Square Knot, depending on how you tie it. If you pull the loose ends of each side of the bow all the way through the knot, you get one or the other depending on how you started. A Granny Knot is a considerably poorer knot that the Square and can work itself apart much more easily leading to untied shoes. Double knotting can help, but if you've been tying Granny Bows the whole time, doubling the knot can compound your problem.

While buying a pair of shoes recently, I was told: "UR DOIN' IT WRONG!"

Since then, I've been slowly trying to retrain myself to time my shoes properly. This is harder than it seems. Three decades of shoe tying are hard to overcome.