填充静态unordered_map局部变量

populating a static unordered_map local variable

本文关键字:map 局部变量 unordered 静态 填充      更新时间:2023-10-16

我有一个使用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中,以便仅在第一次调用函数时插入它们(就像仅在第一次进行内存分配一样)?

可能吗?

在 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();