Note that there are some explanatory texts on larger screens.

plurals
  1. POParameters passed to multiple argument lambda expression
    primarykey
    data
    text
    <p>I just watched <a href="http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-/C9-Lectures-Introduction-to-STL-with-Stephan-T-Lavavej" rel="nofollow">this lecture</a> about STLs by STL.</p> <p>Around 57 minutes into the lecture, we have this code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;algorithm&gt; int main() { std::vector&lt;std::string&gt; v; v.push_back("cat"); v.push_back("antelope"); v.push_back("puppy"); v.push_back("bear"); std::sort(v.begin(), v.end(), [](const std::string&amp; left, const std::string&amp; right) { return left.size() &lt; right.size(); } ); for (std::vector&lt;std::string&gt;::iterator i = v.begin(); i != v.end(); ++i) { std::cout &lt;&lt; *i &lt;&lt; " "; } std::cout &lt;&lt; std::endl; return 0; } </code></pre> <p>As expected, this prints the strings in the vector in increasing order of their lengths. My question is about the lambda expression which is the 3rd argument to the <code>sort</code> function. Internally, what gets passed to the input parameters 'left' &amp; 'right'?</p> <p>I added the line:</p> <pre><code>std::cout &lt;&lt; "left: " &lt;&lt; left &lt;&lt; ", right: " &lt;&lt; right &lt;&lt; std::endl; </code></pre> <p>inside the body of the lambda, and the output I got was:</p> <p><em>left: antelope, right: cat<br> left: antelope, right: cat<br> left: puppy, right: cat<br> left: puppy, right: antelope<br> left: puppy, right: cat<br> left: bear, right: cat<br> left: bear, right: antelope<br> left: bear, right: puppy<br> left: bear, right: cat<br> cat bear puppy antelope</em> </p> <p>So it looks like the 'left' and 'right' arguments are somehow related to the internal sorting algorithm in play. Can anyone shed more light on what exactly is going on?</p> <p>My understanding is that if the lambda were to be a unary function, then it's input argument would have been whatever the iterator is currently pointing to. Is this correct?<br> But with a binary function, the input arguments puzzle me.</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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