Search code examples
c++c++11stl-algorithm

good idiom for empty containers with std::all_of( ) and std:none_of( )?


Both std::all_of( ) and std:none_of( ) return true for empty containers.

Aside from debating the conceptual aspect of this, can someone suggest an idiom that does not call for always checking if the container is empty AND checking for all_of or none_of?

This is bothersome in that using the same predicate in both algorithms on an empty container will indicate that the predicate is true for both ALL and NONE of the elements. So, your (empty) vector is all_of "odd", all_of "even", none_of "odd" and none_of "even".

On a more practical level I am thinking in terms of checking a collection of items for a status, like are any "ready for processing", and expect an empty collection to correspond to "NO, there are no elements ready to be processed". I know I can check if it is empty separately but I am looking for other possibilities.


Solution

  • You could write your own wrapper and use that to modify the result if the container is empty:

    // in your namespace, not std:
    template< class InputIt, class UnaryPredicate >
    bool none_of( InputIt first, InputIt last, UnaryPredicate p )
    {
      return first != last && std::none_of( first, last, p );
    }