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
Release: 2024-11-28 06:33:10
Original
747 people have browsed it

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());
Copy after login

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);
}
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template