What is predicate in C++?

munish picture munish · May 7, 2011 · Viewed 55.7k times · Source

Can you give some example or a link to a topic.

Answer

Andrey Sidorov picture Andrey Sidorov · May 7, 2011

A predicate is a C++ function returning a boolean or an object having a bool operator() member. A unary predicate takes one argument, a binary takes two, and so on. Examples of questions predicates can answer for a particular algorithm are:

  • Is this element what we are looking for?
  • Is the first of two arguments ordered first in our order?
  • Are the two arguments equal?

Almost all STL algorithms take a predicate as last argument.

You can construct new predicates using standard, self-defined, and/or predicate-making classes (here is a good reference).