cross
cross

Reputation: 1068

Is it possible to initialize a std::map with n keys, where n is predefined?

I wonder if it is possible to initialize a std::map with n key:value elements in it, where n is predefined (something similar to array initialization: array[n]).

I am not aware that such a constructor exists for std::map but I thought I could ask just in case.

Alternately what one could do is:

#include <iostream>
#include <map>

int main()
{
   int n = 5;
   std::map<int,double> randomMap;

   for(int i = 0; i < n; ++i)
   {
       randomMap.insert({i,0.9});
   }

   for(auto j: randomMap)
   {
       std::cout<<"key: " << j.first <<"\tvalue: " << j.second << std::endl;
   }

   return 0;
}

Upvotes: 6

Views: 5198

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

Sure, you can use an initializer list, for example

int main()
{
    std::map<int, double> randomMap {{0, 1.5}, {3, 2.7}, {9, 1.9}};
    for (auto const& element : randomMap)
    {
        std::cout << "key: " << element.first << " value: " << element.second << std::endl;
    }
}

Output

key: 0 value: 1.5
key: 3 value: 2.7
key: 9 value: 1.9

Upvotes: 11

Related Questions