开发者

Declaring std::map constants

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 so开发者_如何学Cme 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}};


I was so taken by the Boost.Assign solution to this problem that I wrote a blog post about it about a year and a half ago (just before I gave up on blogging):

The relevant code from the post was this:

#include <boost/assign/list_of.hpp>
#include <map>

static std::map<int, int>  amap = boost::assign::map_list_of
    (0, 1)
    (1, 1)
    (2, 2)
    (3, 3)
    (4, 5)
    (5, 8);


int f(int x)
{
    return amap[x];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜