【问题标题】:Use ranged algorithm on custom container在自定义容器上使用范围算法
【发布时间】:2021-02-12 11:00:50
【问题描述】:

我想升级我的自定义容器以兼容 std::ranges 算法,例如 find_if 和其他算法,如下所示

auto is_satisfy = [](CustomContainer::value_type x) { ... };
std::ranges::find_if(custom_container, is_satisfy);
// instead of std::find_if(custom_container.begin(), custom_container.end(), is_satisfy);

std::ranges::find_if 的签名像

struct find_if_fn {
   template< ranges::input_range R,
            class Proj = std::identity,
            std::indirect_unary_predicate<std::projected<ranges::iterator_t<R>,
                                         Proj>> Pred >
   constexpr ranges::borrowed_iterator_t<R>
   operator()( R&& r, Pred pred = {}, Proj proj = {} ) const
   {
       return (*this)(ranges::begin(r), ranges::end(r), std::ref(pred), std::ref(proj));
   }
};

input_range concept 是什么以及我自己的自定义容器如何支持此功能?

【问题讨论】:

    标签: c++ c++20 c++-concepts std-ranges


    【解决方案1】:

    什么是 input_range 概念

    是这样的:

    template<class T>
      concept input_­range =
        range<T> && input_­iterator<iterator_t<T>>;
    

    在英文中,input_range 是一个迭代器为 input_iterator 的范围。另一方面,范围概念是:

    范围概念定义了允许迭代其元素的类型的要求,方法是提供一个表示范围元素的迭代器和哨兵。

    template<class T>
      concept range =
        requires(T& t) {
          ranges::begin(t); // sometimes equality-preserving
          ranges::end(t);
        };
    

    而 input_iterator 是:

    input_iterator 概念定义了一个类型的要求 可以读取参考值(从要求 间接可读([iterator.concept.readable]))并且可以是 前增量和后增量。 [注 1:与 Cpp17InputIterator 不同 要求([input.iterators]),input_iterator 概念不 需要相等比较,因为迭代器通常与 哨兵。 ——尾注]

    template<class I>
      concept input_­iterator =
        input_­or_­output_­iterator<I> &&
        indirectly_­readable<I> &&
        requires { typename ITER_CONCEPT(I); } &&
        derived_­from<ITER_CONCEPT(I), input_iterator_tag>;
    

    您可以阅读依赖者概念、功能和特征的规范以了解详细信息。

    我自己的自定义容器如何支持此功能?

    简而言之:通过符合上述概念。

    中:提供成员函数beginend,其中前者应返回输入迭代器,后者应返回兼容的哨兵类型(可能与迭代器类型相同或不同)。结束标记应该从一开始就可以到达,并且表示超出范围的最后一个元素。

    一般来说,我建议查看标准容器的 API,以了解它们提供了哪些成员以及它们是如何工作的。将设计复制到您的自定义容器中。


    引用来自最新的标准草案。

    【讨论】:

    • “引用来自最新的标准草案。”。那句话就会过时了:-)
    • @Jarod42 这将是:) 答案是有时间戳的,所以在撰写本文时哪个草案是最新的应该没有什么神秘的。
    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多