STL algorithm or any function?

Is there anything that approximates all of Haskell or any functions as part of the STL? If not, is this a good implementation (I noticed that sgi STL performed a partial specialization if the iterators were random access, although I didn't bother with this)?

template <typename InputIterator, typename Predicate> inline bool all(InputIterator first, InputIterator last, Predicate pred) { while (first != last) { if (!pred(*first)) { return false; } ++first; } return true; } 

Similarly, how would it be best to convert to iterate over two sequences and return true, where BinaryPredicate returns true for all, and false otherwise? I know this is relatively trivial, but it looks like it should be provided by an algorithm, and I want to make sure that I am not missing something.

+4
source share
4 answers

There are no all or any algorithms in C ++, but C ++ 0x adds the std::all_of and std::any_of to the C ++ standard library. Your implementation may support them already.

Since both of these algorithms must check each element in the range (at least until they find a match or a mismatch), there is no reason to specialize them for different types of iterators: the performance when used with iterators forward should be the same as when using with random access iterators.

Your implementation of all beautiful; the Visual C ++ all_of virtually the same, except that it uses a for loop instead of a while loop.

how would it be best to convert to iterate over two sequences and return true, where BinaryPredicate returns true for all, and false otherwise?

This is what std::equal does. You must first check the sizes of the ranges to make sure they are the same size.

+8
source

It looks almost equivalent to std::find_if with the predicate inverted by me.

+5
source

You can use std :: find_if as which returns Iterator last if the predicate returns false for all elements, otherwise it returns an element for which it returns true.

 Iterator it = std::find_if (container.begin (), container.end (), predicate); if (it != container.end ()) // One of them doesn't match 
+2
source

How about foreach from boost? it is not an STL, but is available for any platform.

-1
source

All Articles