c++ - 使用 for_each 将列表初始化为随机变量

标签 c++ boost lambda

我正在尝试使用 for_each 和 lambda 函数将列表初始化为随机整数。我是 boost.lambda 函数的新手,所以我可能没有正确使用它,但以下代码生成了相同数字的列表。每次我运行它时,数字都不同,但列表中的所有内容都是相同的:

srand(time(0));

theList.resize(MaxListSize);

for_each(theList.begin(), theList.end(), _1 = (rand() % MaxSize));

最佳答案

Boost lambda 将在生成仿函数之前评估 rand。您需要绑定(bind)它,所以它会在 lambda 求值时求值:

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp> // for bind
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>

int main()
{
    namespace bl = boost::lambda;
    typedef std::vector<int> int_vec;

    static const size_t MaxListSize = 10;
    static const int MaxSize = 20;

    int_vec theList;
    theList.resize(MaxListSize);

    std::srand(static_cast<unsigned>(std::time(0)));
    std::for_each(theList.begin(), theList.end(),
                    bl::_1 = bl::bind(std::rand) % MaxSize);

    std::for_each(theList.begin(), theList.end(), std::cout << bl::_1 << ' ' );
}

这按预期工作。

但是,正确的解决方案是使用generate_n。为什么要生成一堆 0 来覆盖它们?

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>

int main()
{
    namespace bl = boost::lambda;
    typedef std::vector<int> int_vec;

    static const size_t MaxListSize = 10;
    static const int MaxSize = 20;

    int_vec theList;
    theList.reserve(MaxListSize); // note, reserve

    std::srand(static_cast<unsigned>(std::time(0)));
    std::generate_n(std::back_inserter(theList), MaxListSize,
                        bl::bind(std::rand) % MaxSize);

    std::for_each(theList.begin(), theList.end(), std::cout << bl::_1 << ' ' );
}

关于c++ - 使用 for_each 将列表初始化为随机变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2234508/

相关文章:

c++ - Visual C++ 2010 - 转换 10 GB BYTE 数组的最快方法?

c++ - Ubuntu 上 Boost program_options 代码中的链接错误

c++ - 在 lambda 函数中捕获 boost::asio::thread_pool

ruby - 在 Ruby 1.9 中传递 block 时生成器抛出 "wrong number of arguments"错误

c# - Predicatebuilder group and or queries with inner outer

C++ win 32application : Employee Class array issue

c++ - 如何在内联汇编中实现这个?

c++ - 我如何处理这种情况 C++ sizeof 问题

c++ - 我可以将 Functor 类(重载运算符())传递给需要函数指针的函数吗?如何

VB.NET 简化操作(T)