for循环中的临时函数对象
函数对象 randomElementByWeight 构造函数是否会在循环的每次迭代中被调用,或者编译器是否可以以某种方式优化它?我想确保每次迭代都会调用 rand 函数,并且我认为将它放在函数对象构造函数中会更好。
struct randomElementByWeight
{
double randomNumber;
randomElementByWeight() : randomNumber(rand() / static_cast<double>(RAND_MAX)) {}
bool operator()(const Element& e)
{
if ( (randomNumber -= e.weight) <= 0.0 )
{
return true;
}
return false;
}
};
...
for (int i = 0; i < 3; ++i)
{
iter = find_if(routes.begin(), routes.end(), randomElementByWeight());
}
Does the function object randomElementByWeight constructor get called for every iteration through the loop or can the compiler optimize this away somehow? I want to make sure the rand function is called for each iteration and I think it's nicer to have it in the function object constructor.
struct randomElementByWeight
{
double randomNumber;
randomElementByWeight() : randomNumber(rand() / static_cast<double>(RAND_MAX)) {}
bool operator()(const Element& e)
{
if ( (randomNumber -= e.weight) <= 0.0 )
{
return true;
}
return false;
}
};
...
for (int i = 0; i < 3; ++i)
{
iter = find_if(routes.begin(), routes.end(), randomElementByWeight());
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
顺便说明一下,以下代码:
可以缩写为:
Just a side note, the following code:
can be abbreviated to:
是的,总是为临时变量调用构造函数。除非编译器完全确定省略不会产生副作用,否则它不会优化它。
Yes it does, a constructor is always called for a temporary variable. Unless the compiler knows absolutely sure there are no side-effects if ommitted it won't optimize it away.