Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert values from a vector to a map in c++?

I want to do something like this. Is there a stl algorithm that does this easily?

for each(auto aValue in aVector)
{
    aMap[aValue] = 1;
}
like image 692
John Mcdock Avatar asked Apr 09 '13 21:04

John Mcdock


3 Answers

Maybe like this:

std::vector<T> v;   // populate this

std::map<T, int> m;

for (auto const & x : v) { m[x] = 1; }
like image 197
Kerrek SB Avatar answered Nov 07 '22 08:11

Kerrek SB


You might std::transform the std::vector into a std::map

std::vector<std::string> v{"I", "want", "to", "do", "something", "like", "this"};
std::map<std::string, int> m;
std::transform(v.begin(), v.end(), std::inserter(m, m.end()),
               [](const std::string &s) { return std::make_pair(s, 1); });

This creates std::pairs from the vector's elements, which in turn are inserted into the map.


Or, as suggested by @BenFulton, zipping two vectors into a map

std::vector<std::string> k{"I", "want", "to", "do", "something", "like", "this"};
std::vector<int> v{1, 2, 3, 4, 5, 6, 7};
std::map<std::string, int> m;

auto zip = [](const std::string &s, int i) { return std::make_pair(s, i); };
std::transform(k.begin(), k.end(), v.begin(), std::inserter(m, m.end()), zip);
like image 44
Olaf Dietsche Avatar answered Nov 07 '22 08:11

Olaf Dietsche


If you have a vector of pairs, where the first item in the pair will be the key for the map, and the second item will be the value associated with that key, you can just copy the data to the map with an insert iterator:

std::vector<std::pair<std::string, int> > values {   
    {"Jerry", 1},
    { "Jim", 2},
    { "Bill", 3} };

std::map<std::string, int> mapped_values;

std::copy(values.begin(), values.end(), 
          std::inserter(mapped_values, mapped_values.begin()));

or, you could initialize the map from the vector:

std::map<std::string, int> m2((values.begin()), values.end());
like image 17
Jerry Coffin Avatar answered Nov 07 '22 09:11

Jerry Coffin