Home >Backend Development >C++ >How to Efficiently Extract Keys or Values from a std::map into a Vector?

How to Efficiently Extract Keys or Values from a std::map into a Vector?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 06:33:10763browse

How to Efficiently Extract Keys or Values from a std::map into a Vector?

Retrieve Elements from std::map into Vector: Beyond Functors

To extract keys or values from a std::map, one might instinctively employ functors as demonstrated in the provided code snippet:

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

map<int, int> m;
vector<int> keys;
transform(m.begin(), m.end(), back_inserter(keys), RetrieveKey());

While this approach technically functions, it suffers from code obscuration and execution distance from the target.

Alternative Method: Iterator Loop

A more straightforward solution involves a simple loop over the map's iterators:

for (map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
  keys.push_back(it->first);
}

This method offers clear readability and easy modification to retrieve values instead of keys.

Boost Library Approach

If using the Boost library, one can employ BOOST_FOREACH for even greater simplicity:

pair<int, int> me; // map element type
vector<int> v;
BOOST_FOREACH(me, m) {
  v.push_back(me.first);
}

This approach provides explicitness and conciseness.

In summary, while the functor method remains a valid option, the iterator loop and Boost library approaches offer simpler and more intuitive ways to retrieve elements from a std::map into a vector.

The above is the detailed content of How to Efficiently Extract Keys or Values from a std::map into a Vector?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn