无需测试即可更改循环内部
假设我有以下循环:
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
if(tilesMap[i][j])
(tilesMap[i][j])->Draw(window) ;
}
}
有
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
(tilesMap[i][j])->Draw(window) ;
}
}
什么方法可以使其成为“通用”,即如果某个布尔值为真,我将调用第一个代码段,如果不是,我将调用第二个代码段。 显然,我可以在循环之前进行测试并在右侧循环上进行分支,但是随后我必须复制循环“标头”和内部指令,并且每次更改循环内的代码时都将其更改两次。另一种解决方案是在每次迭代时在 lopp 内进行测试,但这会在运行时进行太多测试。 我还有其他方法可以做到这一点吗?谢谢
编辑:这只是我所知的一个问题,我完全可以复制如此少量的代码
let's say I have the following loops:
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
if(tilesMap[i][j])
(tilesMap[i][j])->Draw(window) ;
}
}
and
for(int i=left; i < right; i++) {
for(int j=top; j < bottom; j++) {
(tilesMap[i][j])->Draw(window) ;
}
}
Is there any way I can make this "generic", ie if some boolean is true, I will call the first code segment, if not I'll call the second code segment.
I obviously could do a test before the loop and branch on the right loop, but then I have to duplicate the loop "header" and the instruction inside too, and change it twice every time I change the code inside the loop. The other solution is to do a test inside the lopp at every iteration, but this would make way too many tests at runtime.
Is there any other way I can do this? thanks
EDIT: this is just a question for my knowledge, I'm perfectly fine with duplicating my code for such small amount
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用指向函数(i,j)的指针。
或者一个物体。如果您使用 C++,您可以采用面向对象的方式,即使用虚拟方法和继承。它将需要大量源代码行,但它将是干净的代码。 :-)
You can use a pointer to a function(i,j).
Or an object. If you use C++, you can do it object oriented way i.e. with a virtual method and inheritance. It will need a lot of source lines, but it will be clean code. :-)
IMO,这段代码足够小,只需复制循环即可。如果有一点点代码重复可以使其更具可读性并有助于提高性能,我会接受。
我想说,在循环内放置测试可能会使其更难以阅读,因为它增加了嵌套深度。
IMO, this code is small enough to just duplicate the loop. I'd be okay with a tiny bit of code-duplication if it makes it more readable and helps performance.
I would say that putting a test inside the loop could make it harder to read since it increases the nesting depth.
分支预测器工作得很好。
也就是说,您可以将两个循环体包装在策略对象中,在循环外部运行一次测试来选择一个,并将循环体委托给策略方法。
Branch predictors work quite well.
That said, you could wrap your two loop bodies in strategy objects, run the test outside of the loop once to choose one, and have the loop body delegate to the strategy method.