我需要堆栈溢出的意见来解决一直关注循环效率的问题.现在,当我开始编程时,"让它工作"是一个重中之重,我的大多数for循环都是这样的.
for (int i = 0; i < N; i++) {;}
Run Code Online (Sandbox Code Playgroud)
然后我就玩了,特别是在C++开发中,预增量可以节省一些调用,并且考虑到这将是N次调用,并且它不会改变我养成习惯的可读性.
for (int i = 0; i < N; ++i) {;}
Run Code Online (Sandbox Code Playgroud)
这已经足够好了一段时间,但专注于可读性,在阅读了Steve McConnell的一些Code Complete之后,我到了这里.
for (int loop_index = 0; loop_index < loop_count; ++loop_index) {;}
Run Code Online (Sandbox Code Playgroud)
这些变量会根据代码的上下文而改变.然后我读了一些关于内置类型构造函数和赋值的Effective C++.而且基本上就是那之间的区别
int i = 42;
Run Code Online (Sandbox Code Playgroud)
和
int i(42);
Run Code Online (Sandbox Code Playgroud)
是前者调用构造函数和赋值运算符,而后者只调用构造函数.所以我在编码的过程中将其纳入了常规.所以我的问题是,这是编写for循环最有效和最易读的方法:
for (int loop_index(0); loop_index < loop_counter; ++loop_index) {;}
Run Code Online (Sandbox Code Playgroud) 我有一个为文明V创建地图的应用程序.作为一个有趣的设计选择,我决定创建一些函数来为我循环遍历地图.这样我就可以将函数指针或lambda函数传递给该函数,该函数遍历整个映射,为每个tile执行某些操作.这背后的推理是,如果我或其他人改变地图的存储方式(从2D数组到2D矢量或其他),人们只需要改变一个函数而不是整个代码库.
现在问题出在这里,首先是一些代码.
错误代码.
case ALL_SNOW:
m.loop_through_limit([] (Tile* t) {
t = new Snow(t->get_x(), t->get_y());
return t;
}, x, y, width, height);
break;
case PTN_ONE:
m.loop_through_limit([&] (Tile* t) {
int cur_x = t->get_x();
int cur_y = t->get_y();
t = new Plains(cur_x, cur_y);
// if (y <= height/4 || y >= (height*3)/4) {
// Top quarter rows and bottom quarter rows
// t = new Ocean(cur_x, cur_y);
// } else if (cur_x <= width/4) {
// Leftmost columns
// t = new …Run Code Online (Sandbox Code Playgroud)