根据我之前提出的问题,这是一个更具体的问题......
如果我有一个带两个参数的函数(一个是必需的,一个是可选的):
码:
template <typename Type>
Type FindMax (std::vector<Type> &myVec, int (*cmp)(Type one, Type two) = CallBack)
/.../
Run Code Online (Sandbox Code Playgroud)
究竟是什么,"int(*cmp)(Type 1 ......)"对编译器说了什么?我想要它说,这是一个比较两个类型Type时使用的函数...即使用关系运算符<,>,=等时.如果用户没有提供任何函数,则使用默认值,否则,使用用户提供的内容......
(*cmp)(第一类,第二类)到底是什么意思?这是一个指向函数的指针,它接受两个参数Type 1和Type 2?关于*之后的内容是否有任何意义,即我可以写(*titsmagee)(Type 1,Type 2)?我假设命名惯例是为了帮助未来的读者?
为了使用"struct",是否需要将所有特定于潜在比较的内容存储在所述结构中?
谢谢!
int (*cmp)(Type one, Type two)
Run Code Online (Sandbox Code Playgroud)
名为的参数cmp是一个返回函数的指针,该函数int接受两个类型的参数Type.
struct Foo
{
int x;
};
int compare(Foo x, Foo y)
{
return (x.x == y.x) ? 0 : (x.x > y.x ? 1 : -1);
}
std::vector<Foo> vec;
FindMax<Foo>(vec, &compare);
Run Code Online (Sandbox Code Playgroud)
你需要cmp这样你可以调用里面的比较函数FindMax:
template <typename Type>
Type FindMax (std::vector<Type> &myVec, int (*cmp)(Type one, Type two) = CallBack)
{
//whatever loop
max = cmp(myVec[i],myVec[j]) >= 0 ? myVec[i] : myVec[j];
}
Run Code Online (Sandbox Code Playgroud)
编辑打破回报:
return (x.x == y.x) ? 0 : (x.x > y.x ? 1 : -1);
Run Code Online (Sandbox Code Playgroud)
?: 是三元条件运算符.
condition ? expression1 : expression2
Run Code Online (Sandbox Code Playgroud)
返回(松散地说)expression1如果condition为true,否则返回 expression2.
那意味着什么:
if (x.x == y.x)
return 0;
else
if (x.x > y.x)
return 1;
else
return -1;
Run Code Online (Sandbox Code Playgroud)
这是您期望比较功能的功能.如果第一个元素大于第二个元素0,1则返回相等,反之则返回-1.
编辑2
struct Foo
{
int x;
};
//Foo has a member x.
Foo f;
//Create a Foo object called f.
f.x;
//Access the member x of the object
Run Code Online (Sandbox Code Playgroud)