(C++) std::is\_sorted
January 11, 2018 · View on GitHub
(C++)
std::is_sorted
std::is_sorted is a C++11 STL algorithm to check if a container is sorted.
#include <algorithm> #include <vector> ///IsSorted checks if a container is sorted. ///From http://www.richelbilderbeek.nl/CppIsSorted.htm template <class T> bool IsSortedStl11(const T& v) { return std::is_sorted(v.begin(),v.end()); } #include <cassert> int main() { std::vector<int> v; v.push_back(3); v.push_back(2); v.push_back(5); v.push_back(1); v.push_back(0); assert(!std::is_sorted(v.begin(),v.end())); std::sort(v.begin(),v.end()); assert(std::is_sorted(v.begin(),v.end())); }
std::is_sorted test
Technical facts
Operating system(s) or programming environment(s)
Lubuntu 12.10 (quantal)
Qt Creator 2.5.2
- G++ 4.7.2
Libraries used:
STL: GNU ISO C++ Library, version
4.7.2
Qt project file: CppIs_sorted.pro
TEMPLATE = app CONFIG += console CONFIG -= qt QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++ -Werror SOURCES += main.cpp
main.cpp
#include <algorithm> #include <functional> #include <vector> ///IsSorted checks if a container is sorted. ///From http://www.richelbilderbeek.nl/CppIsSorted.htm template <class T> bool IsSortedStl98(const T& v) { return std::adjacent_find( v.begin(), v.end(), std::greater<typename T::value_type>()) == v.end(); } ///IsSorted checks if a std::vector is sorted. ///From http://www.richelbilderbeek.nl/CppIsSorted.htm template <class T> bool IsSortedStl98VectorOnly(const std::vector<T>& v) { return std::adjacent_find( v.begin(), v.end(), std::greater<T>()) == v.end(); } ///IsSorted checks if a container is sorted. ///From http://www.richelbilderbeek.nl/CppIsSorted.htm template <class T> bool IsSortedStl11(const T& v) { return std::is_sorted(v.begin(),v.end()); } #include <cassert> int main() { std::vector<int> v; v.push_back(3); v.push_back(2); v.push_back(5); v.push_back(1); v.push_back(0); assert(!IsSortedStl98(v)); assert(!IsSortedStl11(v)); std::sort(v.begin(),v.end()); assert(IsSortedStl98(v)); assert(IsSortedStl11(v)); }