boost lambda 的用法

发布于 2024-08-13 17:39:33 字数 307 浏览 2 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

°如果伤别离去 2024-08-20 17:39:34

似乎您需要使用 延迟函数调用

std::for_each(a.begin(), a.end(), boost::lambda::_1= boost::lambda::bind(rand) );

这是另一个有趣的情况: 延迟常量和变量

Seems like you need to use delayed function call

std::for_each(a.begin(), a.end(), boost::lambda::_1= boost::lambda::bind(rand) );

Here is another interesting situation: Delaying constants and variables

盗琴音 2024-08-20 17:39:34

您的代码相当于以下代码:

using namespace boost::lambda;

srand(time(NULL));

boost::array<int, 100> a;
int i = rand();

std::for_each(a.begin(), a.end(), _1=i);

您想要的是为每个元素调用 rand ;这通常是使用 std::generate 完成的,正如 @MP24 在评论中指出的:

std::generate(a.begin(), a.end(), rand);

Your code is equivalent to the following one:

using namespace boost::lambda;

srand(time(NULL));

boost::array<int, 100> a;
int i = rand();

std::for_each(a.begin(), a.end(), _1=i);

What you want is rand to be invoked for each element; this is usually done using std::generate, as @MP24 noted in a comment:

std::generate(a.begin(), a.end(), rand);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文