Forward Iterator C ++:for_each行为 [英] Forward Iterator C++ : for_each behavior

查看:143
本文介绍了Forward Iterator C ++:for_each行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我们知道foreach是这样的:

So we know that foreach is something like :

template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function f)
  {
    for ( ; first!=last; ++first ) f(*first);
    return f;
  }

我实施了

template <typename T>
class Range

问题是当我使用这个函数和for_Each: p>

The problem is that when I use this function with the for_Each :

static void add1(float &v)
{
  ++v;
}

它进入无限循环,因为第一个!=last

it go in infinite loop because of first "!=" last (it's not first"<"last), so how people do when they implemente their own forward iterator to work with for_each ?

推荐答案

第一个是第一个<last,那么当人们如何实现自己的前向迭代器来使用for_each?你的方法的问题是你的迭代器增量运算符不改变迭代器,而是改变存储的值。这意味着在 for_each 循环中,条件在迭代器的增量运算符中也通过函数修改。

The problem of your approach is that your iterator increment operators do not change the iterator, but rather the stored value. This means that inside the for_each loop, the condition is modified both in the increment operator of the iterator and also through the function.

这篇关于Forward Iterator C ++:for_each行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆