Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the pred field in stl algorithms and how can i use it?

Can somebody explain to me how is the pred field in stl algorithms exactly used?

Thank you

like image 433
Alaa M. Avatar asked Oct 14 '25 13:10

Alaa M.


1 Answers

pred stands for predicate which is basically a callable entity which is either a function, or a functor (or a lambda, which is essentially a functor or function depending on whether it captures variable(s) or not). So a predicate may take one or more argument(s), and returns a boolean value.

Here is an example of std::find_if, one overload of which takes unary predicate as third argument. This predicate is unary because it takes one argument and returns bool:

std::vector<int> v{1,2,3,5,6};
auto it = std::find_if(begin(v), end(v), [](int i) { return i == 3; });

Notice the third argument is a lambda which is used as unary predicate.

In C++03, the example can be this:

bool is_three(int i) { return i == 3; }

std::vector<int>::iterator it = std::find_if(v.begin(), v.end(), is_three);

Note that now is_three which is a function is passed as third argument to std::find_if.

like image 121
Nawaz Avatar answered Oct 17 '25 01:10

Nawaz