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; });
}
成员current
是一个指针,因此它可能始终大于零。您的lambda必须接受迭代器对象,并在函数中取消引用它。请尝试以下操作。
[&](iterType ¤t) {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; });
}