Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Is there STL algorithm to check if the range is strictly sorted?

Tags:

c++

stl

By "strictly" I mean "without equivalent elements".

is_sorted(v.begin(), v.end(), std::less<>()) 

doesn't meet my goal because it returns true for ranges like 1,2,2,4,5.

is_sorted(v.begin(), v.end(), std::less_equal<>()) 

would work according to the implementation given here, but unfortunately is_sorted requires Compare predicate to be strict ordering (Compare(a,a) must be false), and std::less_equal certainly isn't.

So should I write my own loop for this purpose?

like image 865
Dmitry J Avatar asked Apr 04 '17 22:04

Dmitry J


People also ask

What is sorting algorithms in STL?

Sorting Algorithms in STL. We will be studying about three methods under Sorting Algorithms, namely : sort. This function of the STL, sorts the contents of the given range. There are two version of sort() : sort(start_iterator, end_iterator ) : sorts the range defined by iterators start_iterator and end_iterator in ascending order.

How do you sort a range in STL?

partial_sort (start, middle, end, compare_function) : sorts the range from start to end in such a way that the elements before middle are sorted with the help of compare_function and are the smallest elements in the range. This function of the STL, returns true if the given range is sorted.

What are the different types of search algorithms in STL?

=> Look For The Entire C++ Training Series Here. We will discuss each of these types in detail in the following paragraphs. The prominent search algorithm in STL is a binary search. Binary search algorithm operates on a sorted array and searches for the element by dividing the array into half.

What is quick sort in C++ STL?

Sort in C++ Standard Template Library (STL) Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). Internally this function is implemented as Quick-sort. The complexity of it is O(N*log(N)).


1 Answers

Quoting the comment stream:

std::adjacent_find with std::greater_equal should do the trick - it will find the first element that is greater or equal than the next one; if no such element exists, the sequence is strictly increasing.

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v1{0, 1, 2, 3, 40, 41};

    auto i2 = std::adjacent_find(v1.begin(), v1.end(), std::greater_equal<int>());
    if (i2 == v1.end()) {
        std::cout << "The entire vector is sorted in strictly ascending order\n";
    } else {
        std::cout << "The vector is not sorted\n";
    }
}

Example derived from http://en.cppreference.com/w/cpp/algorithm/adjacent_find

like image 199
Robᵩ Avatar answered Nov 04 '22 04:11

Robᵩ