So last week I wrote about [initializing a std::map](http://www.peteware.com/blog/2009/05/copying-a-stdvector-into-a-stdmap/) from two [std::vectors](http://www.cplusplus.com/reference/stl/vector/). How about doing the reverse? How do I get a list of the keys or a list of the values into a vector?
So I wrote a functor, based on [std::unary_function](http://www.cplusplus.com/reference/std/functional/unary_function/), that returns the pair.first and another that returns the [pair.second](http://www.cplusplus.com/reference/std/utility/pair/):
[cc lang="cpp"]
#include
#include
/**
* A functor that returns the first in a pair
*/
template
struct first: public std::unary_function
typedef typename PairType::first_type result_type;
typedef PairType argument_type;
result_type operator()(argument_type &p) const
{
return p.first;
}
result_type operator()(const argument_type &p) const
{
return p.first;
}
};
/**
* A functor that returns the second in a pair
*
*/
template
struct second: public std::unary_function
typedef typename PairType::second_type result_type;
typedef PairType argument_type;
result_type operator()(argument_type &p) const
{
return p.second;
}
result_type operator()(const argument_type &p) const
{
return p.second;
}
};
[/cc]
The first() template functor (from above) is used as the functor that returns the key to the [std::transform()](http://www.cplusplus.com/reference/algorithm/transform/) alogrithm. Here is a little fragment code that uses first(). (The test code part of a larger [CPPUNIT](http://apps.sourceforge.net/mediawiki/cppunit/index.php?title=Main_Page) test suite):
[cc lang="cpp"]
void TestUtils::testFirst()
{
typedef std::map
String2StringMap m;
m["a"] = “0″;
m["z"] = “1″;
m["x"] = “2″;
std::vector
std::transform (m.begin(), m.end(),
std::back_inserter (keys),
first
CPPUNIT_ASSERT_EQUAL (m.size(), keys.size());
CPPUNIT_ASSERT_EQUAL (std::string (“x”), keys[1]);
}
[/cc]