Technology

Getting the keys from a std::map

So last week I wrote about initializing a std::map from two std::vectors. 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, that returns the pair.first and another that returns the pair.second:

/**
 * 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;
    }
};

The first() template functor (from above) is used as the functor that returns the key to the std::transform() alogrithm. Here is a little fragment code that uses first(). (The test code part of a larger CPPUNIT test suite):

void TestUtils::testFirst()
{
    typedef std::map String2StringMap;
    String2StringMap m;
    m["a"] = "0";
    m["z"] = "1";
    m["x"] = "2";
    std::vector    keys;
    std::transform (m.begin(), m.end(),
                    std::back_inserter (keys),
                    elf::first());
    CPPUNIT_ASSERT_EQUAL (m.size(), keys.size());
    CPPUNIT_ASSERT_EQUAL (std::string ("x"), keys[1]);
}

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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.