2014-02-12 135 views
1

我有一个功能,这使得使用unordered_map和它的只有这个功能在我的课,它使用它:填充静态unordered_map局部变量

void my_func(){ 
    static std::unordered_map<int,int> my_map; 

    //I only want this to be done the first time the function is called. 
    my_map[1] = 1; 
    my_map[2] = 3; 
    //etc 

} 

我如何可以插入的元素,以我的静态unordered_map所以他们只在我的函数第一次被调用时插入(就像内存分配只是第一次)?

可能吗?

+0

使用'static bool'作为标志来检查它是否已初始化? – Mine

回答

2

在C++ 11(这你大概使用,否则就不会有一个unordered_map),容器可以通过一个列表初始化器来填充:

static std::unordered_map<int,int> my_map { 
    {1, 1}, 
    {2, 3}, 
    //etc 
}; 

历史上,最彻底的方法是调用返回已填充容器的函数:

static std::unordered_map<int,int> my_map = make_map(); 
+0

感觉MSVC和Intel编译器不允许你的第一个建议。我确实喜欢第二个建议:) – user997112

+0

+1,如果初始化程序列表不起作用(有时它们很古怪),那么'make_map'函数可以是一个lambda表达式。 – Potatoswatter

+0

@ user997112英特尔往往是最符合标准的,而MSVC往往是最不合规的流行实现。 – Potatoswatter