STL 定义了两种类型的 transform功能
第一个是对于一元运算符:
template <class InputIterator, class OutputIterator, class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);
第二个是二元运算符:
template <class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
三元运算符的类似函数的最有效实现是什么?
编辑: 这是我想出的简单实现,但是没有更精简和更优雅的解决方案吗?
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;
}
最佳答案
可以实现一个简单的版本来创建这样的 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;
}
这个版本试图尽可能接近现有的transform
,采用一对first
/last
迭代器,其余的是只是第一个
。这让用户可以确保所有范围都有效,就像二进制转换一样。
至于性能,我同意 ShighShagh 关于性能在这里不太可能成为问题的评论。编译器将比您更好地确定要采取哪些优化,因为每个实例化都可能导致程序员在编写此函数时不可能知道的不同情况。
关于c++ - 最佳 STL 转换——类似三元运算符的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21758718/