Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) GreaterThan

 

GreaterThan is an example functor.

 

 

 

 

 

 

 

 

 

 

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: CppGreaterThan.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= qt
QMAKE_CXXFLAGS += -Wall -Wextra -Weffc++ -Werror
SOURCES += main.cpp

 

 

 

 

 

main.cpp

 

#include <algorithm>
#include <cassert>
#include <functional>
#include <numeric>
#include <vector>

//From http://www.richelbilderbeek.nl/CppFunctorGreaterThan.htm
#pragma GCC diagnostic ignored "-Weffc++"
struct GreaterThan : public std::unary_function<bool,int>
{
  explicit GreaterThan(const int x) : m_x(x) {}
  bool operator()(const int x) const
  {
    return x > m_x;
  }

  private:
  int m_x;
};
#pragma GCC diagnostic pop


const std::vector<int> CreateVector()
{
  std::vector<int> v;
  v.push_back(0);
  v.push_back(1);
  v.push_back(2);
  std::random_shuffle(v.begin(),v.end());
  return v;
}


int main()
{
  const std::vector<int> v = CreateVector();
  assert(std::count_if(v.begin(),v.end(),GreaterThan(-1))==3);
  assert(std::count_if(v.begin(),v.end(),GreaterThan( 0))==2);
  assert(std::count_if(v.begin(),v.end(),GreaterThan( 1))==1);
  assert(std::count_if(v.begin(),v.end(),GreaterThan( 2))==0);

  assert(std::count_if(v.begin(),v.end(),std::not1(GreaterThan(-2)))==0);
  assert(std::count_if(v.begin(),v.end(),std::not1(GreaterThan(-1)))==0);
  assert(std::count_if(v.begin(),v.end(),std::not1(GreaterThan( 0)))==1);
  assert(std::count_if(v.begin(),v.end(),std::not1(GreaterThan( 1)))==2); //FAILS???
  assert(std::count_if(v.begin(),v.end(),std::not1(GreaterThan( 2)))==3);
}

 

 

 

 

 

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