Home >Backend Development >C++ >How to Efficiently Extract Keys and Values from a std::map into Vectors?
Retrieving Keys or Values from a std::map into a Vector
Retrieving all keys or values from a std::map into a vector is a common task, but std::map itself lacks an explicit member function for this purpose. One approach involves defining custom functors, as demonstrated in the provided code:
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"));
This solution manipulates the data outside the map, which may not be ideal in some cases. An alternative approach utilizing a straightforward for-loop offers a clearer and more explicit solution:
map<int, int> m; vector<int> key, value; for (auto it = m.begin(); it != m.end(); ++it) { key.push_back(it->first); value.push_back(it->second); cout << "Key: " << it->first << endl; cout << "Value: " << it->second << endl; }
By iterating through the map in this way, we can extract both keys and values directly into vector containers.
Another option, if using the Boost library, simplifies the process further:
map<int,int> m; pair<int,int> me; // what a map<int, int> is made of vector<int> v; BOOST_FOREACH(me, m) { v.push_back(me.first); cout << me.first << "\n"; }
This version is concise, readable, and provides explicit control over the retrieval process. Selecting the most appropriate method depends on the specific needs and preferences of the developer.
The above is the detailed content of How to Efficiently Extract Keys and Values from a std::map into Vectors?. For more information, please follow other related articles on the PHP Chinese website!