std::is_sorted and strictly less comparison?

前端 未结 3 2073
旧时难觅i
旧时难觅i 2021-02-20 09:51

I do not understand well the std::is_sorted algorithm and its default behaviour. If we look to cppreference, it says that by default std::is_sorted use

3条回答
  •  执笔经年
    2021-02-20 10:38

    You seem to be assuming that it's checking (for the positive case) if element N is less than element N+1 for all elements bar the last. That would indeed not work with just <, though you can use a 'trick' to evaluate <= with < and !: the following two are equivalent:

    if (a <= b)
    if ((a < b) || (!((b < a) || (a < b)))) // no attempt at simplification.
    

    However, it's far more likely that it detects (the negative case) if element N is less than element N-1 for all but the first so that it can stop as soon as it finds a violation. That can be done with nothing more than <, something like (pseudocode):

    for i = 1 to len - 1:
        if elem[i] < elem[i-1]:
            return false
    return true
    

提交回复
热议问题