Can somebody explain to me how is the pred field in stl algorithms exactly used?
Thank you
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With