Switching keys in values in a map

A functor that reverses a pair: first becomes second,
second becomes first. Useful for switching
from a map to another map (or multimap in this example) where
the value becomes the key and the key the value.

std::map<std::string, int> m;
std::multimap<int,std::string> m2;
m["a"] = 0;
m["b"] = 1;
m["c"] = 0;
std::transform (m.begin(), m.end(), std::inserter (m2, m2.begin()),

And the actual code:

template<class PairType>
struct pair_switcher : public std::unary_function<PairType, std::pair<a,b>
 typedef std::pair result_type;
 typedef PairType argument_type;
 result_type operator()(const argument_type &p) const
     return result_type (p.second, p.first);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.