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



// 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(

    const std::map<Key, Value, Compare, Allocator> & theMap,

    typename const std::map<Key, Value, Compare, Allocator>::key_type & key,

    typename std::map<Key, Value, Compare, Allocator>::mapped_type & value



    // Search for the specified key in the map

    auto it = theMap.find(key);


    // NOTE:


    // The above line should be written like this without the C++0x ‘auto’ keyword

    // (which is available in VS2010 a.k.a. VC10, but not in previous versions):


    // std::map<Key, Value, Compare, Allocator>::const_iterator 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;







(Note how the new C++0x’s auto keyword simplifies the code.)

A compilable C++ source code is attached to this post.

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