gpt4 book ai didi

c++ - std::map 初始化(仅一次)

转载 作者:太空宇宙 更新时间:2023-11-03 10:36:40 24 4
gpt4 key购买 nike

我有一个使用 std::map 转换数据的函数

struct HistoParameter
{
int nbins;
float first;
float last;
HistoParameter(int _nbins, int _first, int _last) :
nbins(_nbins), first(_first), last(_last) {};
};

HistoParameter* variable_to_parameter(char* var_name)
{
std::map<const std::string, HistoParameter*> hp;
hp[std::string("ph_pt")] = new HistoParameter(100,0,22000);
hp[std::string("ph_eta")] = new HistoParameter(100,-3,3);
// ...
return hp[var_name];
}

我的结构很轻,但图像可能很重。问题是每次我调用这个函数时它都会创建很多 HistoParameter 对象,也许 switch case 更有效。第一个问题:我在制造垃圾?

第二种方案:

bool first_time = true;
HistoParameter* variable_to_parameter(char* var_name)
{
static std::map<const std::string, HistoParameter*> hp;
if (first_time)
{
hp[std::string("ph_pt")] = new HistoParameter(100,0,22000);
hp[std::string("ph_eta")] = new HistoParameter(100,-3,3);
// ...
}
first_time = false;
return hp[var_name];

还好吗?更好的解决方案?

最佳答案

第二个解决方案对我来说似乎没问题——你可以说:

if ( hp.empty() ) {
// populate map
}

我还会考虑将其设为值映射而不是指针 - 我看不到您在这里需要动态分配:

 std::map <std::string, HistoParameter> hp;

然后:

 hp["ph_pt"] = HistoParameter(100,0,22000);

请注意,您不需要显式的 std::string 转换。或者更好:

 hp.insert( std::make_pair( "ph_pt", HistoParameter(100,0,22000 )));

关于c++ - std::map 初始化(仅一次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2136053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com