[cfe-dev] error with lambda function that results in endless loop

Ben Pope benpope81 at gmail.com
Thu May 3 03:57:02 PDT 2012

On Thursday, May 03, 2012 05:53 PM, Ran Regev wrote:
> Colleagues,
> While working with some c++11 features I have encountered a problem with std::sort;
>> From some reason it was stuck when I tried to sort more than 10 elements.
> I simplified the code to use normal int, instead of my objects, and it gets stuck above 30 elements.
> Here is the code, followed by the compilation command line, followed by the output, followed by more information:
> 12:30:06/auto>  cat sortproblem.cpp
> #include<iostream>
> #include<vector>
> void checkSort( std::vector<int>&  v )
> {
>      std::sort( v.begin(), v.end(),
>          [] (const int&  a1, const int&  a2) ->  bool
>          {
>              return true;
>          }
>      );
> }

 > <snip>

> Surly returning true regardless of the value of the elements has no real meaning and can results in nonsense like a1<a2==true&&  a2<a1==true
> And surly this is a bad idea to write code like this, but still - why it passes 30 and not 31?

This has nothing to do with lambdas.

You already know what the problem is, I'm not sure what you expect to 

std::sort requires a strict weak ordering, always returning true does 
not fulfill that criteria.

Have a look here:

Checked versions of Microsoft’s standard library attempt to catch this 
type of problem, you end up with an assert if I recall, but that's a QOI 

Technically running your ill-defined program is allowed to do anything, 
including getting stuck at 31 elements and appearing to work at 30.


More information about the cfe-dev mailing list