代码之家  ›  专栏  ›  技术社区  ›  ScootyPuff

STL算法全部还是任何函数?

  •  4
  • ScootyPuff  · 技术社区  · 14 年前

    作为STL的一部分,是否有任何近似Haskell的全部或任何函数?如果不是,下面的是一个很好的实现吗(我注意到如果迭代器是随机访问的,那么sgi STL执行了部分专门化,尽管我没有对此感到困扰)?

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

    类似地,如何最好地将其转换为迭代两个序列,并在BinaryPredicate为all返回true,否则返回false时返回true?我知道这是相对琐碎的,但似乎这应该由算法提供,我想确保我没有忽视一些东西。

    4 回复  |  直到 14 年前
        1
  •  8
  •   James McNellis    14 年前

    没有 all any std::all_of std::any_of C++标准库的算法。您的实现可能已经支持这些。

    你实施的 全部的 很好;Visual C++ all_of

    如何最好地将其转换为迭代两个序列,并在BinaryPredicate为all返回true,否则返回false时返回true?

    std::equal 做。您需要首先检查范围的大小,以确保它们的大小相同。

        2
  •  5
  •   Mark B    14 年前

    std::find_if

        3
  •  2
  •   Joe D    14 年前

    如果喜欢,可以使用std::find\返回 Iterator last 如果谓词对所有元素都返回false,否则它将返回返回true的元素。

    Iterator it = std::find_if (container.begin (), container.end (), predicate);
    if (it != container.end ())
        // One of them doesn't match
    
        4
  •  -1
  •   Mee    14 年前