简体   繁体   中英

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.

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

That's why std:: _of() does return false for an empty collection. _of()为空集合返回false的原因。

If the question would be "Are all items finished processing?", then the expected answer would by "Yes, everything is finished." if there weren't any items to be processed in the first place (That's the std::all_of() case).

Similarily, the question "Did no errors occur during processing?" would be answered "Yes, there were no errors." for an empty list (no work -> no errors). This is what std::none_of() checks for.

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 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM