c++ - 最佳 STL 转换——类似三元运算符的模板函数

标签 c++ algorithm stl

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/

相关文章:

c++ - 是否有一种简单的定时锁定算法可以避免多个互斥体上的死锁?

c++ - C1083 : Cannot open include file: math. h: 没有那个文件或目录

c++ - 使用最少代码的 Windows 7 任务栏状态

python - python 实现中的 Strassen 算法错误

c++ - 在 O(logn) 时间内使用 STL 堆实现 Decrease Key

c++ - 不明白为什么while(* ptr++)输入while循环以获取0值(字符串终止符)

c++ - 为类的每个实例分配唯一 ID

algorithm - 为什么堆叠在凸包中

c++ - 定义一个内部有结构的 map

c++ - 具有不可 move 的默认可构造值类型的 map/unordered_map