1

How to copy keys from map to vector. Specifically I have a map<int, int> and I want keys of the map to form a new vector (vector<int>).

So a map (<1,100>; <2,99>) should give a vector of (1,2).

Question here, describes exactly what I need but for values, but the response is too cryptic to understand. I cannot understand how the unary operator function is written. Can somebody explain how it is written?

Community
  • 1
  • 1
Aman Deep Gautam
  • 8,091
  • 21
  • 74
  • 130
  • the unary operator: std::transform( map.begin(), map.end(), std::back_inserter(vec), boost::bind(&MapT::value_type::second,_1) ); takes value associated with each entry from map and binds to the first argument of back_inserter method. in your case you'd use value_type::first – Nandu Oct 19 '15 at 02:25

1 Answers1

3

The accepted answer of the question you linked to in your post has almost everything you need. You need to change just one line:

Instead of

v.push_back( it->second );

use

v.push_back( it->first);

Update, in response to OP's comments

You can use std::transform with a lambda function to extract the keys of a std::map and put them in a std::vector.

Sample program:

#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <iterator>

using namespace std;

int main()
{
   map<int, int> m{{1, 20}, {2, 40}};
   vector<int> keys;

   // Retrieve all keys
   transform(m.begin(), m.end(), back_inserter(keys), [](std::pair<int, int> p) { return p.first;} );

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

Output:

1
2
Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270