STL定义了两种转换函数
第一个是对于一元运算符:
template <class InputIterator, class OutputIterator, class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);
Run Code Online (Sandbox Code Playgroud)
第二个是二元运算符:
template <class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
Run Code Online (Sandbox Code Playgroud)
对于三元运算符,最有效的类似函数实现是什么?
编辑:这是我提出的简单实现,但是不是更精简和更优雅的解决方案吗?
template <class InputIterator1, class InputIterator2, class InputIterator3,
class OutputIterator, class TrenaryOperation>
OutputIterator transform3(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator3 first3, OutputIterator result,
TrenaryOperation trenary_op)
{
while (first1 != last1) {
*result = trenary_op(*first1, *first2, *first3);
++result; ++first1; ++first2; ++first3;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
可以实现一个简单的版本来创建 n 元变换,如下所示:
template <class Functor, class OutputIterator,
class Input1, class ... Inputs>
OutputIterator transform(Functor f, OutputIterator out,
Input1 first1, Input1 last1,
Inputs ... inputs)
{
while(first1 != last1)
*out++ = f(*first1++, *inputs++...);
return out;
}
Run Code Online (Sandbox Code Playgroud)
这个版本试图尽可能接近现有版本transform,采用一个first/last一对迭代器,其余的只是firsts。这让用户需要确保所有范围都有效,就像二进制转换一样。
至于性能,我同意 ShighShagh 的评论,即性能在这里不太可能成为问题。编译器将比您更好地确定要采取哪些优化,因为每个实例化都可能导致程序员在编写此函数时不可能知道的不同情况。