c++ - STL std::变换

标签 c++ stl

transform() 算法有两种形式,我喜欢第一种。

这是第二个模板的规范:

template <class InputIterator1, class InputIterator2,
          class OutputIterator, class BinaryOperation>
  OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
                            InputIterator2 first2, OutputIterator result,
                            BinaryOperation binary_op);

我的书上说,

In the second form, the transformation is applied using a binary operator function that receives the value of an element from the sequence to be transformed as in its first parameter and an element from the second sequence as its second parameter.

q1。为什么第二个序列没有输入迭代器参数来指示第二个序列的结尾?即为什么 transform() 中没有 InputIterator last2 参数?

q2。当第一个和第二个序列的长度不相等时会发生什么?

q3。 block 引用文本表示二元运算符函数。那么该运算符函数在这种情况下意味着什么?任何二元函数都无效吗?

最佳答案

q1. Why is there no input iterator parameter for the second sequence indicating the end of second sequence?

因为无论如何,第二个序列必须至少与第一个序列一样长。该算法知道,当到达第一个序列的末尾时,它的工作就完成了。

q2. What happens when the length of the first and second sequence is unequal?

如果第二个序列比第一个序列短,则会出现未定义的行为。否则,如果第二个更长,也不会发生什么坏事;其余元素将被忽略。

q3. The blockquoted text says binary operator function. So what does that operator function mean in this context?

它的第一个参数是第一个序列中的元素N,第二个参数是第二个序列中的元素N。它可以是任何可以这样称呼的东西,例如普通函数、类似函数的对象(例如 std::function)、lambda、通过 std::bind 绑定(bind)的东西等等。唯一重要的是它可以使用 () 语法调用。

我推荐一些关于“函数对象”和“仿函数”的互联网研究。

关于c++ - STL std::变换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47366436/

相关文章:

c++ - 围绕 glutMainLoop 执行程序的其余部分?

c++ - 展开操作期间遇到无效或未对齐的堆栈

c++ - 为什么我不能使用带有 ofstream 的 Windows 环境路径来编写文本文件?

c++ - 删除 std::map 中的特定元素

c++ - 使用队列的 Phantom Bug(STL 库),Windows/MingW/G++

c++ - 将 float 存储为 short int。令人困惑的结果

c++ - 前向声明模板指针

c++ - 为什么我不能用 std::unordered_map 替换 std::map

c++ - vector<string *> 让我困惑

围绕 2 个字符串流 ("dialogue"模仿的 C++ 包装器)