Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Boost lambda will evaluate <code>rand</code> before the functor is made. You need to <code>bind</code> it, so it's evaluated at lambda evaluation time:</p> <pre><code>#include &lt;boost/lambda/lambda.hpp&gt; #include &lt;boost/lambda/bind.hpp&gt; // for bind #include &lt;algorithm&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;iostream&gt; #include &lt;vector&gt; int main() { namespace bl = boost::lambda; typedef std::vector&lt;int&gt; int_vec; static const size_t MaxListSize = 10; static const int MaxSize = 20; int_vec theList; theList.resize(MaxListSize); std::srand(static_cast&lt;unsigned&gt;(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 &lt;&lt; bl::_1 &lt;&lt; ' ' ); } </code></pre> <p>This works as expected.</p> <p>However, the <em>correct</em> solution is to use <code>generate_n</code>. Why make a bunch of 0's just to overwrite them?</p> <pre><code>#include &lt;boost/lambda/lambda.hpp&gt; #include &lt;boost/lambda/bind.hpp&gt; #include &lt;algorithm&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;iostream&gt; #include &lt;vector&gt; int main() { namespace bl = boost::lambda; typedef std::vector&lt;int&gt; 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&lt;unsigned&gt;(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 &lt;&lt; bl::_1 &lt;&lt; ' ' ); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload