c++ – What is a predicate function?

Question:

I am learning C ++. In the literature, one of the functions is called predicate. What does this mean, or is it such a translation?

Answer:

Let's consider such a task. We have, say, a vector of integers and we only want to display positive numbers.

How do we do it?

void out(const vector<int>& v)
{
    for(auto i: v) 
        if (i > 0) cout << i << " ";
}

And if you display everything, more than 5?

void out(const vector<int>& v)
{
    for(auto i: v) 
        if (i > 5) cout << i << " ";
}

It seems? Yes. So it pulls to unite them into

void out(const vector<int>& v, int value)
{
    for(auto i: v) 
        if (i > value) cout << i << " ";
}

But what if we only want to display the even ones? Only those for which the sine is positive?

All this can be summarized, for example, like this:

void out(const vector<int>& v, bool(*)(int) pred)
{
    for(auto i: v) 
        if (pred(i)) cout << i << " ";
}

Where pred is a function that checks some condition, a predicate . And only those numbers for which the pred function will return true will be displayed. And how we write it is our business. For instance,

bool pred(int i) { return i > 5; }

That, in essence, is all. The rest is a function, or a lambda, a template or not, from how many arguments, etc. etc. – not the point is important. Predicative function – checking some condition, predicate , for its (their) argument (s).

Well, predicates are widely used in the algorithms of the standard library.

Scroll to Top