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

问题描述 投票:0回答:2

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; });
    }
c++ templates iterator type-conversion value-type
2个回答
0
投票

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

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

0
投票

答案是:

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; });
}

© www.soinside.com 2019 - 2024. All rights reserved.