为什么C ++标准库中没有std :: transform_n函数? [英] Why is there no std::transform_n function in the C++ standard library?

查看:81
本文介绍了为什么C ++标准库中没有std :: transform_n函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在草案这是故意的吗?如果没有,那么该如何为将来的标准版本提出建议呢?

Is this intentional? If not, how would one go about suggesting this for a future version of the standard?

这是我的实现方式:

    template<typename _InputIterator, typename Size, typename _OutputIterator, typename _UnaryOperation>
_OutputIterator transform_n(_InputIterator __first, Size __n, _OutputIterator __result, _UnaryOperation __op) {
    for(Size i=0;i<__n;++i)
        *__result++ = __op(*__first++);
    return __result;
}


template<typename _InputIterator1, typename Size, typename _InputIterator2, typename _OutputIterator, typename _BinaryOperation>
_OutputIterator transform_n(_InputIterator1 __first1, Size __n, _InputIterator2 __first2, _OutputIterator __result, _BinaryOperation __binary_op) {
    for(Size i=0;i<__n;++i)
        *__result++ = __binary_op(*__first1++, *__first2++);
    return __result;
}

推荐答案

这是另一种可能的实现,它表明已经存在具有等效功能的库函数:

Here's another possible implementation, which shows that there is already a library function with equivalent functionality:

template<typename _InputIterator,
         typename _OutputIterator,
         typename _UnaryOperation>
_OutputIterator transform_n(_InputIterator __first,
                            size_t __n,
                            _OutputIterator __result,
                            _UnaryOperation __op) {
      return std::generate_n(__result, __n,
                             [&__first, &__op]() -> decltype(auto) {
                                return __op(*__first++);
                             });
}

正如@TonyD在评论中提到的那样,这具有迫使转换按顺序进行的效果,但是如果输入迭代器参数实际上只是一个输入迭代器,已经是这种情况了.

As @TonyD mentions in a comment, this has the effect of forcing the transformation to happen in order, but that would already be the case if the input iterator argument is really just an input iterator.

根据@TC的建议,我将lambda更改为具有 decltype(auto)的返回类型,(如果我理解正确的话)可以允许通过输出迭代器移动语义.由于它是C ++ 14的功能,因此需要最新的编译器.

As per the suggestion by @T.C., I changed the lambda to have a return type of decltype(auto), which (if I understand correctly) could allow move semantics through the output iterator. That requires a recent compiler, since it's a C++14 feature.

这篇关于为什么C ++标准库中没有std :: transform_n函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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