Ste*_*lvo 6 c++ stl-algorithm c++11
我在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;
}
Run Code Online (Sandbox Code Playgroud)
这是另一种可能的实现,它表明已经存在具有等效功能的库函数:
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++);
});
}
Run Code Online (Sandbox Code Playgroud)
正如 @TonyD 在评论中提到的,这具有强制转换按顺序发生的效果,但如果输入迭代器参数实际上只是一个输入迭代器,情况就已经是这样了。
编辑:根据 @TC 的建议,我将 lambda 更改为返回类型decltype(auto),这(如果我理解正确的话)可以允许通过输出迭代器移动语义。这需要最新的编译器,因为它是 C++14 功能。