How to retrieve all keys (or values) from a std::map?

Posted by Owen on Stack Overflow See other posts from Stack Overflow or by Owen
Published on 2008-09-21T03:23:58Z Indexed on 2010/05/08 13:08 UTC
Read the original article Hit count: 149

Filed under:
|

This is one of the possible ways I come out:

struct RetrieveKey
{
    template <typename T>
    typename T::first_type operator()(T keyValuePair) const
    {
        return keyValuePair.first;
    }
};

map<int, int> m;
vector<int> keys;

// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());

// Dump all keys
copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n"));

Of course, we can also retrieve all values from the map by defining another functor RetrieveValues.

Is there any other way to achieve this easily? (I'm always wondering why std::map does not include a member function for us to do so.)

© Stack Overflow or respective owner

Related posts about c++

Related posts about stl