STL 谓词必须是纯谓词吗?

发布于 2024-11-09 17:13:02 字数 456 浏览 0 评论 0原文

我所说的“纯”谓词是指它们依赖于它们的论点。那么以下函数对象是否是一个有效的谓词,可用于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

牵强ㄟ 2024-11-16 17:13:02

“仅取决于它们的参数”实际上意味着“如果使用相同的参数再次调用,则必须返回与之前相同的结果”。如果您的(特定的)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 from someObj::someFn for particular instances of T2 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).

梦醒时光 2024-11-16 17:13:02

是的,没关系。

只需确保整个操作满足排序所需的稳定性要求即可。

Yes, that's fine.

Just make sure that the entire operation provides whatever stability requirements the sort needs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文