可能重复:
循环中i ++和++ i之间的区别?
任何人都可以解释这些之间的区别:
for(unsigned col = 0; col < n; ++col, num_to_fill >>= 1U)
{
for(unsigned row = num_to_fill; row < (1U << n); row += (num_to_fill * 2))
{
std::fill_n(&output[col][row], num_to_fill, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
和
for(unsigned col = 0; col < n; col++, num_to_fill >>= 1U)
{
for(unsigned row = num_to_fill; row < (1U << n); row += (num_to_fill * 2))
{
std::fill_n(&output[col][row], num_to_fill, 1);
}
}
Run Code Online (Sandbox Code Playgroud)
什么时候col=0,ex.1 Output[col][row]将在output[1][row]和ex.2 Output[col][row]中output[0][row].我对吗 ?
问题2:使用>>= 1U 而不是有/= 2任何区别?
Ste*_*hen 21
它对col循环内的值没有任何影响- 假设col是一个原始值.如果col是一个类,前缀和后缀"++"运算符可能会重载以执行两个不同的操作,尽管我认为这是不好的做法.请考虑以下示例:
#include <iostream>
using namespace std;
int main() {
for(int i = 0; i < 10; i++) {
cout << i << endl;
}
cout << endl;
for(int i = 0; i < 10; ++i) {
cout << i << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这两个都打印出0到9,尽管你预先增加一个,然后在另一个中增加.的增量i发生在无论是否使用前或后增量循环的每个运行结束.我相信预增量更有效,因为 - 我可能在这里错了 - 编译器不需要使用临时变量1.但是这只有在你循环很长时间时才会注意到(和当然'更多的计算罪是以效率的名义而不是任何其他单一的原因'.)
至于问题2:
问题2:使用>> = 1U代替=/2会有什么不同吗?
不太可能.如果编译器没有进行优化,则位移会更快,但很可能你的编译器会将其优化为位移.
作为旁注,我通常会发现做unsigned variableName(也就是说,放弃int)不良做法 - 尽管C++会在int任何缺少的地方推迟,但对我来说它的可读性较差.
1.:斯蒂芬评价(一个不同斯蒂芬;))指出, - "预增量为标准库容器迭代器更有效,但它的基本类型没有什么不同,因为复制的整数比复制的较大迭代器更便宜(特别是std :: set和std :: map iterators)."