使用函子摆脱 IF 语句
Get rid of IF statements by using functors
请教我如何在以下循环中使用函子(或任何其他更好的方法)来摆脱这些 if 语句:
//Loop over each atom
std::string temp_name ;
float dst;
for (pdb::pdb_vector:: size_type i=0; i < data.size(); ++i)
{
if (type == 0)
{
//choose by residue name
temp_name = data[i].residue_name;
} else {
//choose by atom name
temp_name = data[i].atom_name;
}
//compare the name and extract position if matched
if (temp_name.compare(name) == 0)
{
if (direction.compare("x") == 0)
{
dst = ::atof(data[i].x_coord.c_str());
} else if ((direction.compare("y") == 0)) {
dst = ::atof(data[i].y_coord.c_str());
} else {
dst = ::atof(data[i].z_coord.c_str());
}
}
}
您可以将if(type == 0)
替换为三元运算符:
// if(type == 0) ...
temp_name = (type == 0 ? data[i].residue_name : data[i].atom_name);
但是,如果您尝试类似的东西,其余的检查似乎只会降低可读性。
相关文章:
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 需要有关此 if 语句的帮助
- 转换器练习:跳过 if 语句和 if 语句
- 避免在 C++ 中的 if 语句中递增
- 如果仍然不满足要求,如何使 if 语句重复?
- do while 循环中的 if 语句以 yes 或 no 结尾
- 为什么在此C++代码中触发此 if 语句?
- 如何基于平台在制作文件中制作if语句?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ If 语句,从其他语句重复