I want to create a method inside a class (but I think this is irrelevant) that sorts a vector according to the bool value returned by a particular function... I read that it is possible but I don't know how to do it...
I would like to call the function and put (for example) >
, or <
, as a parameter, so that I don't have to create two almost identical functions.
How I imagine the body of the function:
for (int i = 0 ; i < DIM - j; i++)
{
if (some_function(v[i], v[i+1]))
{
int temp;
temp = v[i];
v[i] = v[i+1];
v[i+1] = temp;
}
}
You can do this by passing in a function object:
template <typename Op>
void f(Op op) {
// ...
if (op(v[i], v[i+1])) // ...
}
and call it like this:
f(std::less{}); // for <
f(std::greater{}); // for >
Of course, f
here is just an example, but you just need to add a template parameter to your own function in this way.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments