gpt4 book ai didi

c++ - 有条件地逐行读取文件

转载 作者:搜寻专家 更新时间:2023-10-31 01:33:34 26 4
gpt4 key购买 nike

现在我有代码:

if (minimizator_weighted) {
while (dataFile >> t >> e >> sigma) { // read data file value by value
/* some code */
}
}
else {
while (dataFile >> t >> e) { // all the same but will not read standard deviation
/* almost the same code */
}
}

如您所见,ifelse 流程之间的唯一区别是 while 循环的条件。我想知道是否有可能优化该代码段并重新使用代码?如果我能写一些这样的东西就好了:

while ((minimizator_weighted) ? (dataFile >> t >> e >> sigma) : (dataFile >> t >> e)) { ... }

但我不确定这个技巧是否正确......你能给我一些优化建议吗?谢谢!

编辑这是完整的代码片段

if (minimizator_weighted) {
while (dataFile >> t >> e >> sigma) { // read data file value by value
data_set::pt point;
point.t = t;
point.e = e;
point.c_vis = 0.0;
point.c_invis = 0.0;

if (std::abs(sigma) <= GSL_SQRT_DBL_MIN) // check for division-by-zero error
sigma = 1.0;

point.sigma = sigma;

set.curve.push_back(point); // store point

data_numPoints++; // collect some stats
set.curveAvg += e;
}
}
else {
while (dataFile >> t >> e) { // all the same but will not read standard deviation
data_set::pt point;
point.t = t;
point.e = e;
point.c_vis = 0.0;
point.c_invis = 0.0;

set.curve.push_back(point);

data_numPoints++;
set.curveAvg += e;
}
}

最佳答案

添加一个间接级别

bool read_data_line1(istream& dataFile, T& t, E& e, Sig& sigma)
{ return dataFile >> t >> e >> sigma; }

bool read_data_line2(istream& dataFile, T& t, E& e, Sig&)
{ return dataFile >> t >> e; }

auto read_data_line_func = minimizator_weighted ? read_data_line1 : read_data_line2;
while(read_data_line_func(dataFile, t, e, sigma))
{
data_set::pt point;
point.t = t;
point.e = e;
point.c_vis = 0.0;
point.c_invis = 0.0;

if (minimizator_weighted)
{
if (std::abs(sigma) <= GSL_SQRT_DBL_MIN) // check for division-by-zero error
sigma = 1.0;
point.sigma = sigma;
}

set.curve.push_back(point); // store point

data_numPoints++; // collect some stats
set.curveAvg += e;
}

关于c++ - 有条件地逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41124382/

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