|
Boost : |
From: Michael Goldshteyn (mgoldshteyn_at_[hidden])
Date: 2006-01-30 13:14:25
It is often the case that one is dealing with key value pairs when using the
STL containers. Sometimes, I have found the need to extract either the key
or the value from these pairs as part of a call to a standard C++ algorithm.
Unfortunatelly, unless one is using the SGI implementation of STL, function
objects such as select1st and select2nd are not available. So, I started to
look for a boost equivalent and finally found it in the bind library. Here
are the mechanisms, with the std prefix omitted for brevity:
Given:
MyMap mymap; // A map of some key type to some value type
MyVector myvector; // A vector of elements either of key type or value type,
depending on requirements
--- // Copy all keys from the map to the vector, which is assumed to containe elements of key type: // Implementation using select1st, when available (e.g. SGI STL extensions) transform(mymap.begin(),mymap.end(),back_inserter(myvector),select1st<MyMap::value_type>()); // Implementation using boost::bind transform(mymap.begin(),mymap.end(),back_inserter(myvector),boost::bind(&MyMap::value_type::first,_1)); // Copy all keys from the map to the vector, which, in this case, is assumed to containe elements of value type: // Implementation using select2nd, when available transform(mymap.begin(),mymap.end(),back_inserter(myvector),select2nd<MyMap::value_type>()); // Implementation using boost::bind transform(mymap.begin(),mymap.end(),back_inserter(myvector),boost::bind(&MyMap::value_type::second,_1)); --- I hope this helps anyone else that needs similar functionality and doesn't want to reinvent the wheel. Thanks, Michael Goldshteyn
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk