Monday, February 05, 2007

make_pair is your friend

One common newbie code smell I've seen a lot of recently is the unnecessary definition of a typedef for a pair of items:

typedef std::pair <Type1, Type2> myPairForMap;

typedef std::map  <Type1, Type2> myMapType;


myMapType m_Map;

The idea is that you can do this:

m_Map.insert( myPairForMap(foo, bar) );

What many people seem to not understand is that there is a more elegant way - use std::make_pair:

m_Map.insert( std::make_pair(foo, bar) );

make_pair is a templated function that returns a pair of items.  It's a simple function so I'll repeat it here in its entirety:

template <class T1, class T2>

pair<T1, T2> make_pair(const T1& x, const T2& y) {

    return pair<T1, T2>(x, y);


See?  It detects what types you're passing in and returns a pair containing the items.  No need to define the pair typedef.


Greyson said...

I prefer

typedef std::map< a1, a2 > myMap;
myMap.insert( myMap::value_type( a1(), a2() ) );

Anonymous said...