Boost lambda оценивает rand
до создания функтора. Вам нужно bind
, чтобы оно оценивалось во время лямбда-оценки:
#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 << ' ' );
}