简体   繁体   中英

Declaring std::map constants

How to declare std map constants ie,

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.

在C ++ 0x中,它将是:

map<int, int> m = {{1,2}, {3,4}};

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 - eg {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';
}

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];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM