Tuesday, June 10, 2014

C++: make the simple case broken

I've been programming C++ for twenty years, and I learned something yesterday about a fundamental class that I use a lot...

int main(int argc, char **argv)
{
   std::map<int, int> myMap;
   myMap.insert(std::make_pair(0, 1));
   myMap.insert(std::make_pair(0, 2));
   printf("%d\n", myMap[0]);
   return 0;
}

What should this program print?  1 or 2?  If you said 2, you'd be horribly wrong!

Because, sometimes, you just want your insert operations to fail.

If you don't want total failure, you need to write:

int main(int argc, char **argv)
{
   std::map<int, int> myMap;
   myMap.insert(std::make_pair(0, 1));
   std::pair::iterator, bool> i = myMap.insert(std::make_pair(0, 2));
   if (!i.second)
      i.first->second = 2;
   printf("%d\n", myMap[0]);
   return 0;
}

That's why I love C++.

No comments: