我有模板功能。通过使用函数std :: for_each用此容器中的最大数替换每个正数

template函数获得2个迭代器,开始和结束迭代器。 模板数据类型iterType是迭代器类型。尝试将当前迭代器值等于lambda函数中的最大值时出现错误: [&](iterType* current) {if (current > 0) current = max; }

    template<typename iterType>
    void modify_each(iterType beg,iterType end) //3.3 #17
    {
        typename iterType::value_type max = *beg;
        for (auto it = beg; it != end; it++)
        {
            if (max < *it)  max = *it;
        }

        std::for_each(beg,end,[&](iterType* current) {if (current > 0) current = max; });
    }
gouihk7 回答:我有模板功能。通过使用函数std :: for_each用此容器中的最大数替换每个正数

成员current是一个指针,因此它可能始终大于零。 您的lambda必须接受迭代器对象,并在函数中取消引用它。请尝试以下操作。

[&](iterType &current) {if (*current > 0) *current = max; });
,

答案是:

template<typename iterType>
void modify_each(iterType beg,iterType end) //3.3 #17
{
    typename iterType::value_type max = *beg;
    for (auto it = beg; it != end; it++)
    {
        if (max < *it)  max = *it;
    }

    std::for_each(beg,end,[=](typename iterType::value_type& current) {if (current > 0) current = max; });
}

,

问题是您的lambda输入错误的类型。

您可以这样做:

template<typename It>
void modify_each(It beg,It end) //3.3 #17
{
    if (beg == end) return; // Empty range
    const auto it = std::max_element(beg,end);

    std::for_each(beg,[&](auto& current) { if (current > 0) current = *it; });
}

如果您没有通用Lambda,则可以使用decltype(*beg)而不是auto&
或者,您可以使用std::iterator_traits<It>中的type。

本文链接:https://www.f2er.com/3101915.html

大家都在问