我正在尝试使用 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/