boost lambda 的用法
我是 boost 的新手,并尝试编写一些简单的程序来理解它。在下面的代码中,我尝试用随机数填充数组。这是我的代码:
using namespace boost::lambda;
srand(time(NULL));
boost::array<int,100> a;
std::for_each(a.begin(), a.end(), _1=rand());
但看起来 rand()
仅被评估一次,并且我的数组包含每个元素的相同值。有人能指出这段代码有什么问题吗?
I am new to boost and trying to write some simple programs to understand it. Here in the following piece of code I am trying to fill an array with random numbers. Here is my code:
using namespace boost::lambda;
srand(time(NULL));
boost::array<int,100> a;
std::for_each(a.begin(), a.end(), _1=rand());
But it looks like rand()
is getting evaluated only once and my array is containing the same values for every element. Can anybody point what is wrong with this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
似乎您需要使用 延迟函数调用
这是另一个有趣的情况: 延迟常量和变量
Seems like you need to use delayed function call
Here is another interesting situation: Delaying constants and variables
您的代码相当于以下代码:
您想要的是为每个元素调用 rand ;这通常是使用 std::generate 完成的,正如 @MP24 在评论中指出的:
Your code is equivalent to the following one:
What you want is rand to be invoked for each element; this is usually done using std::generate, as @MP24 noted in a comment: