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?
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.
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.
=> 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.
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)).
Quoting the comment stream:
std::adjacent_find
withstd::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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With