重构使用if语句的重复范围检查

时间:2017-11-06 19:42:21

标签: c++ c++11 if-statement conditional

下面我附上代码,附带逻辑语句。通过查看此代码,我可以看到它非常重复。

我的任务:9x9网格是给我的,里面有9个盒子,我试图让索引从(startRow/Col)到(startRow/Col+2)开始循环。

vector<int> findBox(int row, int col){
    int startRow;
    int startCol;
    if(row <= 2){
        startRow = 0;
    } else if(row > 2 && row <= 5){
        startRow = 3;
    } else if(row > 5 && row <= 8){
        startRow = 6;
    }
    if(col <= 2){
        startCol = 0;
    } else if (col > 2 && col <= 5){
        startCol = 3;
    } else if(col > 5 && col <= 8){
        startCol = 6;
    }
    vector<int> v;
    v.push_back(startRow);
    v.push_back(startCol);
    return v;
}

我正在寻找有人向我解释更好的方法。或者我应该尝试重构代码并使用开关?

谢谢。

的Jak

2 个答案:

答案 0 :(得分:3)

无需使用开关。利用整数除法将丢弃余数:

int startRow{row / 3 * 3};
int startCol{col / 3 * 3};

然后该功能变为:

vector<int> findBox(int row, int col){
    int startRow{row / 3 * 3};
    int startCol{col / 3 * 3};
    vector<int> v;
    v.push_back(startRow);
    v.push_back(startCol);
    return v;
}

答案 1 :(得分:1)

也许

vector<int> findBox (int row, int col)
 { return { (row - row % 3), (col - col % 3) }; }