使用函子摆脱 IF 语句

Get rid of IF statements by using functors

本文关键字:IF 语句      更新时间:2023-10-16

请教我如何在以下循环中使用函子(或任何其他更好的方法)来摆脱这些 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);

但是,如果您尝试类似的东西,其余的检查似乎只会降低可读性。