Is there anything approximating Haskell's all or any functions as part of the STL? If not, is the below a good implementation (I noticed the sgi STL performed partial specialization if the iterators were random access, though I have not bothered 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 this best be transformed to iterate two sequences, and return true where a BinaryPredicate returns true for all, and false otherwise? I know this is relatively trivial, but it seems like this should be provided by algorithm, and I want to make sure I'm not overlooking something.
Working knowledge of template classes is a prerequisite for working with STL. STL has 4 components: Algorithms.
The Standard Template Library, or STL, is a C++ library of container classes, algorithms, and iterators; it provides many of the basic algorithms and data structures of computer science. The STL is a generic library, meaning that its components are heavily parameterized: almost every component in the STL is a template.
Description. The C++ function std::algorithm::all_of() Returns true if predicate returns true for all the elements in the range of first to last.
By returning the end of an input sequence, the algorithms indicate failure. For instance, find(begin, end, x) returns end if it can not find x.
There are not all
or any
algorithms in C++ currently, but C++0x adds std::all_of
and std::any_of
algorithms to the C++ standard library. Your implementation may support these already.
Since both of these algorithms need to test every element in the range (at least until they find a match or mismatch), there isn't any reason to specialize them for different types of iterators: the performance when used with forward iterators should be the same as the performance when used with random access iterators.
Your implementation of all
is fine; the Visual C++ all_of
implementation is effectively the same, except that it uses a for loop instead of a while loop.
how would this best be transformed to iterate two sequences, and return true where a BinaryPredicate returns true for all, and false otherwise?
This is what std::equal
does. You'll need to check the sizes of the ranges first to ensure that they are of the same size.
This looks almost equivalent to std::find_if
with the predicate inverted to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With