racarate racarate - 1 month ago 5
C++ Question

is_partitioned behavior when no elements satisfy predicate

I was surprised to see the following code return true:

bool isSadPancake(char c) { return c == '-'; }

string pancakes = "+++";

bool isParitioned = is_partitioned(pancakes.begin(), pancakes.end(), isSadPancake);

The documentation I see online said
returns true if all the elements in the range [first, last) that satisfy the predicate appear before all elements that don't. In this case, no elements that satisfy the predicate appear so I expected a return value of false. Is this expected behavior? Where in the standard can I find more details?

Answer Source

Another way of seeing it is that all elements that satisfy the predicate do in fact appear before those that don't. All zero of them.

An even better way of thinking about it is like this: What would it mean for the sequence to not be partitioned? That means you should be able to find first an element that does not satisfy the predicate, followed by one that does. And you cannot find such a counterexample in your sequence.