Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard C++ function object for taking apart a std::pair?

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.

like image 942
Michael Kristofik Avatar asked Dec 16 '08 21:12

Michael Kristofik


People also ask

What is std :: pair C++?

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.

Can std :: function be empty?

The stored callable object is called the target of std::function . If a std::function contains no target, it is called empty.

Why did we need to use an std :: function object?

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.

How do you initialize a pair in C++?

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'};


1 Answers

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));
like image 89
Johannes Schaub - litb Avatar answered Nov 16 '22 23:11

Johannes Schaub - litb