Please explain why this code is crashing?
#include <vector>
#include <cassert>
#include <algorithm>
int main() {
std::vector<int> vt = {1,2,3,4};
assert(std::is_sorted(vt.begin(), vt.end(), [](const auto& a, const auto& b){ return true;}));
}
>Solution :
The comparison function (the lambda expression) is incorrect. It returns always true for vt[i] < vt[j] and for vt[j] < vt[i]. As a result the call of the algorithm has undefined behavior.
From the C++ Standard:
For algorithms other than those described in 25.4.3 to work correctly,
comp has to induce a strict weak ordering on the values.
For example the algorithm can be implemented the following way
template<class ForwardIterator, class Compare>
bool is_sorted( ForwardIterator first,
ForwardIterator last,
Compare comp )
{
auto prev = first;
while ( first != last && ++first != last && !comp( *first, *prev ) )
{
++prev;
}
return first == last;
}
As you can see the expression !comp( *first, *prev ) will at once return false for a sorted sequence.