std::is_sorted and strictly less comparison?

前端 未结 3 2098
旧时难觅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:35

    Even if you only have the < operator you can figure out if two numbers are equivalent not necessarily equal.

    if !(first < second) and !(second < first)
    then first equivalent to second

    In addition, as paxdiablo's solution actually mentioned first, you could implement is_sorted as going up the list and continually checking for < not to be true, if it is ever true you stop.

    Here is the correct behavior of the function from cplusplus.com

    template 
      bool is_sorted (ForwardIterator first, ForwardIterator last)
    {
      if (first==last) return true;
      ForwardIterator next = first;
      while (++next!=last) {
        if (*next<*first)     // or, if (comp(*next,*first)) for version (2)
          return false;
        ++first;
      }
      return true;
    }  
    

提交回复
热议问题