迭代的概念

Christopher Diggins在他的blog文章introducing the Iterable Concept中提到了迭代的概念,且看他的定义的实例:

In pseudo-C++ this translates to roughly:

concept Iterable  {

  public {

    typedef value_type;

    template<typename Procedure>

    void for_each(Procedure proc);

  }

}

 

Example 1: Outputting all Elements from an Iterable

struct putter {

  putter(std::ostream& o, char delim = ' ') : out(x) { }

  template<typename T> void operator()(T& x) {

    out << x << delim; 

  }

  std::ostream& out;

};

 

putter put(std::ostream& o) {

  return putter(o);

}

 

template<typename Iterable>

void print_iterable(Iterable& i) {

  i.for_each(put(std::cout));

}

 

Example 2: Concatenation of Iterable Collections

It is easy to concatenate two completely different Iterable collections, to create a new type which can be used whereever a Iterable is called for.

template<typename Iterable1, typename Iterable2>

struct cat {

  cat(Iterable1& i1, Iterable2& i2) 

    : iterable1(i1), iterable2(i2)

  { }

  template<typename Procedure>

  void for_each(Procedure proc) {

    iterable1.for_each(proc);

    iterable2.for_each(proc);

  } 

  typedef typename Iterable1::value_type value_type;

  Iterable1& iterable1;

  Iterable2& iterable2;

};

 

Example 3: Adapting a Container to an Iterable

Any class modeling a Container concept, can be trivially converted to an Iterable concept:

template<typename Container>

struct container_to_iterable {

  container_to_iterable(Container& x) :

    container(x)

  { }

  template<typename Procedure>

  for_each(Procedure p) {

    typename Container::iterator iter = container.begin();

    typename Container::iterator last = container.end();

    while (iter != last) {

      p(*iter++);

    }

  }

  Container& container;

}

常规的迭代器概念是从数据(指针)的角度定义的,属于单体;而这里的定义是从操作(遍历)的角度定义,属于整体。(这里的Procedure是一个函数对象,类似于C#的delegate)。

思维比较新颖。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值