2010-02-10 5 views
1

for_each 및 lambda 함수를 사용하여 임의의 정수로 목록을 초기화하려고합니다. boost.lambda 함수가 새로 추가 되었기 때문에이 코드를 잘못 사용할 수도 있지만 다음 코드는 같은 번호의 목록을 생성합니다. 나는 그것을 실행할 때마다 수는 다르지만 목록에 모든 것이 동일 다음 펑이 이루어지기 전에for_each를 사용하여 임의의 변수로 초기화 목록

srand(time(0)); 

theList.resize(MaxListSize); 

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

답변

7

부스트 람다 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 << ' '); 
} 
+0

감사합니다. Roger. :) – GManNickG

+0

아, 훌륭한 답변입니다. – Demps