我需要在std::transform中使用哪种输出迭代器来实现 vector 加法分配:

template<typename T>
std::vector<T>& operator+=(std::vector<T>& lhs, std::vector<T> const& rhs)
{
    if (lhs.size() == rhs.size())
    {
        std::transform(lhs.begin(), lhs.end(), rhs.begin(), /*Output Iterator*/, std::plus<T>());
        return lhs;
    }
    throw std::invalid_argument("operands must be of same size");
}
std::transform通过以下方式实现:
template<class InputIt1, class InputIt2,
         class OutputIt, class BinaryOperation>
OutputIt transform(InputIt first1, InputIt last1, InputIt first2,
                   OutputIt d_first, BinaryOperation binary_op)
{
    while (first1 != last1) {
        *d_first++ = binary_op(*first1++, *first2++);
    }
    return d_first;
}

因此,OutputIt需要从lhs.begin()开始,并将所有值替换为lhs.end()。我确定已经实现了某种标准功能。

最佳答案

您只需再次传递lhs.begin():您想要用新值覆盖lhs的现有值。

关于c++ - `std::transform`的 vector 加法赋值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24325069/

10-12 00:02
查看更多