重构使用 if 语句的重复范围检查
Refactoring repeated range checks which use if statements
下面我附上代码,带有逻辑语句。通过查看此代码,我可以看到它非常重复。
我的任务: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;
}
我正在寻找有人来解释我更好的方法。还是我应该尝试重构代码并使用开关?
谢谢。
杰克
无需使用开关。利用整数除法,这将丢弃余数:
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;
}
也许
vector<int> findBox (int row, int col)
{ return { (row - row % 3), (col - col % 3) }; }
?
相关文章:
- 运行时错误:矢量下标超出范围:正在检查空集
- 如何范围检查 C++14 个用户定义的文本?
- 检查私有成员变量是否在一定范围内,如果没有调整
- 实现编译检查以避免C++嵌套范围
- 如何在c/c++中检查两个任意内存范围是否重叠
- 检查IP是否在其他IP网络范围内,并查找下一个可用IP
- C++范围 - v3 概念::valid_expr 检查,带有尾随", 42"
- 在 c++ 中检查 if 条件中的向量位置范围
- 范围检查检测到的检测代码和超出范围的错误访问
- 如何在块复制期间矢量化范围检查
- 初始检查以查看子字符串是否在范围内
- 检查范围的元素是否可以移动?
- 优化的范围检查并返回值
- 在转换为较小的数值类型之前执行范围检查的安全、跨平台方法是什么
- 重构使用 if 语句的重复范围检查
- 使用范围检查和带符号的size_type扩展std::vector
- 使用正则表达式进行范围检查
- 带范围检查的自制迭代器
- 编译时触发std::vector的范围检查
- 矢量超出范围/范围检查