为什么C ++标准库中没有std :: transform_n函数?

时间:2015-05-28 03:21:12

标签: c++ c++11 stl-algorithm

我在C ++标准的草案N4431中没有提到transform_n函数。

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

以下是我将如何实现它:

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

1 个答案:

答案 0 :(得分:3)

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

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在注释中提到的那样,这会强制转换按顺序发生,但如果输入迭代器参数实际上只是一个输入迭代器,那就已经是这种情况了。

编辑:根据@ T.C。的建议,我将lambda更改为返回类型为decltype(auto),如果我理解正确的话,可以允许通过输出迭代器移动语义。这需要最近的编译器,因为它是C ++ 14的特性。