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;
}
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.
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)) ).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With