c++ - How to retrieve all keys (or values) from a std::map and put them into a vector? -


this 1 of possible ways 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 keys transform(m.begin(), m.end(), back_inserter(keys), retrievekey());  // dump keys copy(keys.begin(), keys.end(), ostream_iterator<int>(cout, "\n")); 

of course, can retrieve values map defining functor retrievevalues.

is there other way achieve easily? (i'm wondering why std::map not include member function so.)

while solution should work, can difficult read depending on skill level of fellow programmers. additionally, moves functionality away call site. can make maintenance little more difficult.

i'm not sure if goal keys vector or print them cout i'm doing both. may try this:

map<int, int> m; vector<int> v; for(map<int,int>::iterator = m.begin(); != m.end(); ++it) {   v.push_back(it->first);   cout << it->first << "\n"; } 

or simpler, if using boost:

map<int,int> m; pair<int,int> me; // map<int, int> made of vector<int> v; boost_foreach(me, m) {   v.push_back(me.first);   cout << me.first << "\n"; } 

personally, boost_foreach version because there less typing , explicit doing.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -