Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring std::map constants

Tags:

c++

stl

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.

like image 303
Chandan Shetty SP Avatar asked Dec 02 '22 03:12

Chandan Shetty SP


2 Answers

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';
}
like image 73
Tony Delroy Avatar answered Dec 23 '22 13:12

Tony Delroy


In C++0x, it will be:

map<int, int> m = {{1,2}, {3,4}};
like image 32
Matthew Flaschen Avatar answered Dec 23 '22 12:12

Matthew Flaschen