This is a more specific question based on a question I asked earlier…
If I have a function that takes two parameters (one required, one optional):
- an STL container such as a vector
- an “optional” comparison function that serves as a relational overload and returns the maximum value, whatever that is, in the vector…
Code:
template <typename Type>
Type FindMax (std::vector<Type> &myVec, int (*cmp)(Type one, Type two) = CallBack)
/.../
WHAT exactly, does the “int (*cmp)(Type one…)” say to the compiler? I want it to say, here’s a function to use when comparing two of type Type…ie when using the relational operators <, >, =, etc. If no function is supplied by the user then use the default, otherwise, use what the user provides…
What exactly does the (*cmp)(Type one, Type two) say? Here’s a pointer to a function that takes two parameters Type one and Type two? Is there any significance as to what comes after the *, ie could I write (*titsmagee)(Type one, Type two)? I’m assuming the naming convention is to help future readers?
For this to work with a “struct” does anything specific to the potential comparisons to be made need to be stored within said struct?
Thanks!
The parameter named
cmpis a pointer to a function returningintthat takes two parameters of typeType.You need
cmpso you can call the comparison function insideFindMax:EDIT Breaking down the return:
?:is the ternary conditional operator.returns (loosely speaking) expression1 if
conditionis true, expression2 otherwise.So what that means is:
It’s what you expect the comparison function to do. Return
0for equality,1if the first element is bigger than the second, and-1for the inverse.EDIT 2