初始化静态映射的正确方法是什么?我们是否需要一个静态函数来初始化它?
当前回答
下面是使用2元素数据构造函数的另一种方式。不需要函数来初始化它。没有第三方代码(Boost),没有静态函数或对象,没有技巧,只有简单的c++:
#include <map>
#include <string>
typedef std::map<std::string, int> MyMap;
const MyMap::value_type rawData[] = {
MyMap::value_type("hello", 42),
MyMap::value_type("world", 88),
};
const int numElems = sizeof rawData / sizeof rawData[0];
MyMap myMap(rawData, rawData + numElems);
既然我写了这个答案,c++ 11就过时了。你现在可以使用新的初始化列表功能直接初始化STL容器:
const MyMap myMap = { {"hello", 42}, {"world", 88} };
其他回答
如果你被c++ 98所困,不想使用boost,这里有一个解决方案,当我需要初始化一个静态映射时,我使用:
typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] =
{
elemPair_t( 1, 'a'),
elemPair_t( 3, 'b' ),
elemPair_t( 5, 'c' ),
elemPair_t( 7, 'd' )
};
const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );
使用c++ 11:
#include <map>
using namespace std;
map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};
使用Boost。分配:
#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;
map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
这类似于PierreBdR,但没有复制映射。
#include <map>
using namespace std;
bool create_map(map<int,int> &m)
{
m[1] = 2;
m[3] = 4;
m[5] = 6;
return true;
}
static map<int,int> m;
static bool _dummy = create_map (m);
你可以试试:
std::map <int, int> mymap =
{
std::pair <int, int> (1, 1),
std::pair <int, int> (2, 2),
std::pair <int, int> (2, 2)
};
除了使用的好答案
const std::map<int, int> m = {{1,1},{4,2},{9,3},{16,4},{32,9}}
还有一种可能是直接调用lambda,这在一些情况下是有用的:
const std::map<int, int> m = []()->auto {
std::map<int, int> m;
m[1]=1;
m[4]=2;
m[9]=3;
m[16]=4;
m[32]=9;
return m;
}();
显然,一个简单的初始化列表在从头开始用文字值编写时更好,但它确实开辟了其他可能性:
const std::map<int, int> m = []()->auto {
std::map<int, int> m;
for(int i=1;i<5;++i) m[i*i]=i;
m[32]=9;
return m;
}();
(显然,如果你想重用它,它应该是一个正常的函数;这确实需要最新的c++。)