1

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?

Nigel Hawkins
  • 824
  • 1
  • 8
  • 23
  • possible duplicate of [What is wrong with `std::set`?](http://stackoverflow.com/questions/5397616/what-is-wrong-with-stdset) – Nawaz May 25 '11 at 05:49
  • Yes. See accepted answer in possible duplicate : [What is wrong with `std::set`?](http://stackoverflow.com/questions/5397616/what-is-wrong-with-stdset) – Nawaz May 25 '11 at 05:50
  • Yes. You can read that in the link I've provided in my previous comment. – Nawaz May 25 '11 at 06:02
  • I don't see this as a duplicate. Yes, the information might be gathered from that other (much more lengthy) question, but it's certainly not a duplicate. – DevSolar May 25 '11 at 06:40
  • @Nawaz: Sorry, I deleted the comment you just replied to after reading that link but before your reply appeared. – Nigel Hawkins May 25 '11 at 06:45

2 Answers2

2

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).

Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
1

Yes, that's fine.

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

Adam
  • 16,808
  • 7
  • 52
  • 98