How to declare std map constants i.e.,
int a[10] = { 1, 2, 3 ,4 };
std::map <int, int> MapType[5] = { };
int main()
{
}
In the about snippet it is possible to give values 1,2,3,4 to integer array a, similarly how to declare some constant MapType values instead of adding values inside main() function.
UPDATE: with C++11 onwards you can...
std::map<int, int> my_map{ {1, 5}, {2, 15}, {-3, 17} };
...or similar, where each pair of values - e.g. {1, 5}
- encodes a key - 1
- and a mapped-to value - 5
. The same works for unordered_map
(a hash table version) too.
Using just the C++03 Standard routines, consider:
#include <iostream>
#include <map>
typedef std::map<int, std::string> Map;
const Map::value_type x[] = { std::make_pair(3, "three"),
std::make_pair(6, "six"),
std::make_pair(-2, "minus two"),
std::make_pair(4, "four") };
const Map m(x, x + sizeof x / sizeof x[0]);
int main()
{
// print it out to show it works...
for (Map::const_iterator i = m.begin();
i != m.end(); ++i)
std::cout << i->first << " -> " << i->second << '\n';
}
In C++0x, it will be:
map<int, int> m = {{1,2}, {3,4}};
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