迭代的概念

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)。

思維比較新穎。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章