Does anyone know if there's a de-facto standard (i.e., TR1 or Boost) C++ function object for accessing the elements of a std::pair? Twice in the past 24 hours I've wished I had something like the keys
function for Perl hashes. For example, it would be nice to run std::transform on a std::map object and dump all the keys (or values) to another container. I could certainly write such a function object but I'd prefer to reuse something that's had a lot of eyeballs on it.
std::pair is a class template that provides a way to store two heterogeneous objects as a single unit. A pair is a specific case of a std::tuple with two elements.
The stored callable object is called the target of std::function . If a std::function contains no target, it is called empty.
It lets you store function pointers, lambdas, or classes with operator() . It will do conversion of compatible types (so std::function<double(double)> will take int(int) callable things) but that is secondary to its primary purpose.
Another way to initialize a pair is by using the make_pair() function. g2 = make_pair(1, 'a'); Another valid syntax to declare pair is: g2 = {1, 'a'};
boost::bind
is what you look for.
boost::bind(&std::pair::second, _1); // returns the value of a pair
Example:
typedef std::map<std::string, int> map_type;
std::vector<int> values; // will contain all values
map_type map;
std::transform(map.begin(),
map.end(),
std::back_inserter(values),
boost::bind(&map_type::value_type::second, _1));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With