我正在尝试使用for_each和lambda函数将列表初始化为随机整数.我是boost.lambda函数的新手,所以我可能会错误地使用它,但下面的代码生成了相同数字的列表.每次运行它时,数字都不同,但列表中的所有内容都是相同的:
srand(time(0));
theList.resize(MaxListSize);
for_each(theList.begin(), theList.end(), _1 = (rand() % MaxSize));
Run Code Online (Sandbox Code Playgroud)
在构造仿rand函数之前,增强lambda将进行评估.你需要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 << ' ' );
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作.
但是,正确的解决方案是使用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 << ' ' );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
730 次 |
| 最近记录: |