STL算法全部还是任何功能? [英] STL algorithm all or any function?

查看:193
本文介绍了STL算法全部还是任何功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么近似Haskell的所有或任何功能作为STL的一部分?如果没有,是下面一个很好的实现(我注意到sgi STL执行部分专门化,如果迭代器是随机访问,虽然我没有打扰这)。

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


$ b <其中BinaryPredicate对所有返回true,否则为false?我知道这是相对微不足道,但似乎这应该由算法提供,我想确保我不会忽视的东西。

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.

推荐答案

目前C ++中没有 all 任何算法, C ++标准库的code> std :: all_of 和 std :: any_of 算法。

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.

all 是罚款; Visual C ++ all_of 实现是完全相同的,除了它使用for循环而不是while循环。

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.


如何最好地转换为迭代两个序列,并返回true,其中BinaryPredicate为所有返回true,否则返回false?

how would this best be transformed to iterate two sequences, and return true where a BinaryPredicate returns true for all, and false otherwise?

这是 std :: equal 的用法。您需要先检查范围的大小,以确保它们的大小相同。

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.

这篇关于STL算法全部还是任何功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆