whiteSkar
whiteSkar

Reputation: 1644

C++ Is there a way to initialize unordered_map using contents of vector as keys and custom values?

Let's say I have a vector

vector<int> vect;
vect.push_back(2);
vect.push_back(3);

Now I want an unordered_map with those 2 and 3 as keys and 0 as default values for all those keys.

Is there a way to do it?

I tried doing

unordered_map<int, int> myMap(vect.begin(), vect.end());

hoping it would initialize with what's in the vector as keys and default int value.

However, it couldn't.

I mean, I can always just iterate the vector and manually insert pairs.

I just want to know if I can do it as a one liner during declaration.

Upvotes: 3

Views: 3170

Answers (1)

Jack
Jack

Reputation: 133567

Actually a simple one liner is enough, but not on declaration:

vector<int> vect = { 2, 3, 4};
unordered_map<int,int> map;
transform(vect.begin(), vect.end(), inserter(map, map.end()), [] (int v) { return make_pair(v, 0); });

Upvotes: 1

Related Questions