填充静态unordered_map局部变量
populating a static unordered_map local variable
我有一个使用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();
相关文章:
- 使用的未初始化局部变量'Quick'
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- Gnuplot_i.hpp C++接口绘制局部变量而不是文件
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++中静态方法的局部变量范围
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- 离开范围后如何保护局部变量的值?
- 局部变量名称冲突
- C++ lambda:如何'freeze'局部变量的值?
- 我应该使我的局部变量常量还是可移动的
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 返回对局部变量 - C++ 的引用
- 是否可以影响 C++ 中回调函数的局部变量?
- 警告 C4101 未引用的局部变量
- 线程局部变量的初始化顺序