Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdmap

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;
}
like image 746
cross Avatar asked Jun 02 '15 13:06

cross


People also ask

How do you initialize a map with default value?

To initialize the map with a random default value below is the approach: Approach: Declare a structure(say struct node) with a default value. Initialize Map with key mapped to struct node.

How do you initialize a map with 0?

What exactly do you want to initialize to zero? map's default constructor creates empty map. You may increase map's size only by inserting elements (like m["str1"]=0 or m. insert(std::map<std::string,int>::value_type("str2",0)) ).

Can a map have 2 Keys C++?

Implement a MultiKeyMap in C++A MultiKeyMap is a map that offers support for multiple keys. It is exactly the same as a normal map, except that it needs a container to store multiple keys. A simple solution to implement a MultiKeyMap in C++ is using std::pair for the key.


1 Answers

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
like image 110
Cory Kramer Avatar answered Sep 19 '22 12:09

Cory Kramer