Lookup in std::map

The STL is a very powerful and highly-customizable C++ library (for example, you can provide custom allocators for its containers), but my impression is that sometimes the public interfaces of some classes lack some useful and convenient methods.

One example is std::map: both ATL’s CAtlMap and .NET BCL’s Dictionary classes offer a convenient lookup method (CAtlMap::Lookup and Dictionary.TryGetValue respectively).

Unfortunately, there is nothing similar in STL’s std::map. The logic flow of operations for this class is:

1. call the map::find method passing the key; this method returns an iterator;

2. if the returned iterator equals map::end, the key is not contained in the map;

3. if the returned iterator is valid, the value associated with the given key can be found in iterator->second.

That’s not very intuitive and convenient (IMHO). Fortunately, we can embedd this sequence of operations in a template function, as follows:

//------------------------------------------------------------------------
// FUNCTION: lookup
//
// DESCRIPTION:
// Given an instance of std::map, this function checks if the specified key
// is contained in the map.
// If so, the function copies the value associated with the key in 'value'
// parameter, and returns true.
// If the key is not contained in the map, the function returns false
// (and the 'value' parameter is undefined).
//------------------------------------------------------------------------
template <class Key, class Value, class Compare, class Allocator>
bool lookup(
  std::map<Key, Value, Compare, Allocator> const& theMap,
  typename std::map<Key, Value, Compare, Allocator>::key_type const& key,
  typename std::map<Key, Value, Compare, Allocator>::mapped_type & value
)
{
  // Search for the specified key in the map
  auto it = theMap.find(key);
 
  // If the key is not found in the map, just return false
  if (it == theMap.end())
  {
    return false;
  }
 
  // Key found in map.
  // Copy the associated value back to the caller
  value = it->second;
 
  // Key found
  return true;
}

EDIT 2010-12-15: Thanks Stephan ‘STL’ for enlightment on a template argument deduction issue.

EDIT 2017-01-12: Used Auto SyntaxHighlighter for C++ source code.