Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) C++11 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

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

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));
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml