Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

std::is_sorted return false when lambda return always true

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;}));
}

https://godbolt.org/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading