STL 谓词必须是纯谓词吗?
我所说的“纯”谓词是指它们仅依赖于它们的论点。那么以下函数对象是否是一个有效的谓词,可用于 std::sort
// A predicate for sorting objects of type T2 that relies on an
// object of type T1.
class APredicate {
T1 &someObj;
APredicate(T1 &someObject) : someObj(someObject) {};
bool operator() (T2 thing1, T2 thing2) {
return someObj.someFn(thing1) < someobj.someFn(thing2);
}
}
这是否有效?始终有效?或者它取决于 someObj.SomeFn() 实际做什么?
By "pure" predicates I mean they only depend on their arguments. So is the following function object a valid predicate for use in say, std::sort
// A predicate for sorting objects of type T2 that relies on an
// object of type T1.
class APredicate {
T1 &someObj;
APredicate(T1 &someObject) : someObj(someObject) {};
bool operator() (T2 thing1, T2 thing2) {
return someObj.someFn(thing1) < someobj.someFn(thing2);
}
}
Is this ever valid? Always valid? Or does it depend on what someObj.SomeFn() actually does?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
“仅取决于它们的参数”实际上意味着“如果使用相同的参数再次调用,则必须返回与之前相同的结果”。如果您的(特定的)
someObj
实例没有改变对于T2
的特定实例从someObj::someFn
返回什么的想法< em>是“纯粹”。只要条件在谓词的特定实例的生命周期内成立(STL 通过值获取谓词,因此每个集合或操作都有自己的实例),它就是正确的(显然它必须满足任何特定集合或算法的其他要求)。
The "only depends on their arguments" actually means "if called again with the same arguments, must return the same result as previously". If your (particular instance of)
someObj
does not change it's mind on what to return fromsomeObj::someFn
for particular instances ofT2
it is "pure".As long as the condition holds for lifetime of the particular instance of the predicate (STL takes predicates by value, so each collection or operation have their own instance), it is correct (obviously it has to satisfy any other requirement of the particular collection or algorithm).
是的,没关系。
只需确保整个操作满足排序所需的稳定性要求即可。
Yes, that's fine.
Just make sure that the entire operation provides whatever stability requirements the sort needs.