二、C++迭代器的两种实现方式 (Range for和C#、Java中的foreach)

来源:互联网 发布:什么是数据割接 编辑:程序博客网 时间:2024/06/05 23:07

一、迭代器概述

  这个标题其实有点“标题党”的含义,因为C++在标准库中的实现迭代器的方式只有一种,也就是为类定义begin()和end()函数,C++11增加了range for语句,可以用来遍历迭代器中的元素。实现迭代器的第二种方式,就是用C++模拟C#和Java中的迭代器模式,并且我们可以定义出自己的foreach语句。除此之外,迭代器可能还有很多种实现的方法,各个库也会多自己的迭代器的实现有所定义,在这里只要明白迭代器的本质意义即可。

  迭代器,也称作游标,是一种设计模式,我们可以对它进行递增(或选择下一个)来访问容器中的元素,而无需知道它内部是如何实现的。

  很多语言提供foreach语句来访问容器中的每一个元素,其实也就是调用容器中的迭代器,抽象地来说就是:

  foreach ( 元素 : 容器 ) { ... }

  上面的代码等效于:

  for ( 游标=获得迭代器的开头,获得迭代器的末尾; 游标 != 迭代器末尾; 游标移动一个单位 ) {...} // C++ 的迭代器模式

  或者:

  while ( 迭代器游标移动一个单位(返回是否存在下一个单位)) { ... } // C#、Java的迭代器模式,可以用迭代器.Current之类的方法返回游标所指向的元素

二、C++中的迭代器实现方式

  迭代器其实是一个类,要自定义一个迭代器,就要重载迭代器的!=、解引用(*)、++运算符,以便它在range for语句中使用。range for 是C++11中新增的语句,如我们对一个集合使用语句for (auto i : collection ) 时,它的含义其实为:
for ( auto __begin = collection.begin(), auto __end = collection.end(); __begin != __end(); ++__begin ) { i = *__begin; ... //循环体 }

  begin和end是集合的成员函数,它返回一个迭代器。如果让一个类可以有range for的操作,它必须:
  · 拥有begin和end函数,它们均返回迭代器
  · end函数返回一个指向集合末尾,但是不包含末尾元素的值,即用集合范围来表示,一个迭代器的范围是 [ begin, end ) 一个左闭右开区间
  对于迭代器,它的要求至少是:
  · 必须重载++、!=和解引用(*)运算符;迭代器看起来会像一个指针
  · 迭代器必须可以通过++最后满足!=条件,这样才能够终止循环

  下面给出最简单的实现代码。我们定义一个CPPCollection类,里面有个字符串数组,我们让它能够通过range for将每个字符串输出来。

#include <iostream>class CPPCollection {public:    class Iterator{    public:        int index;        CPPCollection& outer;        Iterator(CPPCollection &o, int i) : outer(o), index(i) { }        void operator++(){            index++;        }        std::string operator*() const{            return outer.str[index];        }        bool operator !=(Iterator i){            return i.index != index - 1;        }    };public:    std::string str[10] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};    Iterator begin() {        return Iterator(*this, 0);    }    Iterator end() {        return Iterator(*this, 9);    }};

  我们定义了个内部的嵌套类Iterator,并为它重载了++、*、!=运算符。由于C++中的内部嵌套类与外围的类没有联系,为了访问外部类对象的值,我们必须要传入一个引用(或指针,本例中传入引用)。Iterator的自增方法其实就是增加内部的一个索引值。判断!=的方法是和另外一个迭代器做比较,这个迭代器一般是集合的末尾,当我们的索引值不等于末尾的索引值-1( [begin, end) )时,认为迭代器已经达到了末尾。
  在CPPCollection类中,定义了begin()、end()分别返回开头、结束迭代器,调用如下代码:
    CPPCollection cpc;    for (auto i : cpc){        std::cout << i << std::endl;    }
  即可遍历集合中的所有元素了。
  在泛型算法中,为了对集合中的每一个元素进行操作,我们通常要传入集合的迭代器头、迭代器尾,以及谓词,例如std::find_if(vec.begin(), vec.end(), ...),这种泛型算法其实就是在迭代器的首位反复迭代,然后运行相应的行为。

三、模拟C#(Java)中的迭代器实现方式

  C#和Java的迭代器实现方式较为类似,在这里以C#为例,我用C++来模拟它的实现。C#中,可迭代的类继承IEnumerable接口,它声明了一个方法GetEnumerator,返回一个迭代器。迭代器继承IEnumerator接口,接口定义了MoveNext()方法:将游标移动一个单位,并返回是否还可以移动;Reset()方法:游标归位; Current属性:返回当前游标所指向的值(在C#中,Current是一个属性,为了模拟它,在C++中将它定义为一个函数),并且用只包含抽象函数的类来模拟接口:
#define interface structtemplate <typename T>interface IEnumerator {    virtual T& Current() = 0;    virtual bool MoveNext() = 0;    virtual void Reset() = 0;    virtual ~IEnumerator<T>() { };};template <typename T>interface IEnumerable {    virtual IEnumerator<T>& GetEnumerator() = 0;    virtual ~IEnumerable () { };};

为了自定义一个foreach“关键字”,可以用宏定义来进行迭代器的等效替代:
#define foreach(item, collection)                                           \auto &__item_enumerator = collection.GetEnumerator();                       \__item_enumerator.Reset();                                                  \while (item = __item_enumerator.Current(), __item_enumerator.MoveNext())

  当我们使用foreach的时候,宏展开自动展开为调用集合类collection的GetEnumerator()函数来获得一个迭代器的引用,复位之,并将当前值赋予item,迭代器向前移动。需要注意的是,我们在代码中不能重复定义__item_enumerator变量,且类型一定要为auto&:auto变量不会保留引用符号,且如果不是引用(或指针),会触发拷贝构造函数,从而失去对象的多态性。
  如同刚才一样,我们定义一个集合类:
class CSharpCollection : public IEnumerable<std::string>{public:    class Enumerator : public IEnumerator<std::string> {    public:        CSharpCollection &outer;    //外部类        int index = 0;  //下标        Enumerator (CSharpCollection &o) : outer(o){        }        bool MoveNext() override {            index++;            if (index <= 10) return true;            delete this;            return false;        }        void Reset() override {            index = 0;        }        std::string &Current() override {            return outer.str[index];        }        ~Enumerator (){            std::cout << "Enumerator 被析构" << std::endl;        }    };public:    std::string str[10] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"};    IEnumerator<std::string>& GetEnumerator() override{        return *new Enumerator(*this);    }};
  需要注意的是,凡是体现多态性的函数,返回值必须为引用或者指针,且不得为栈中的临时变量,因此我们调用完GetEnumerator()后,要将生成的迭代器删除,删除的代码写在了MoveNext()内,当游标不可移动的时候,迭代器被删除。

  以后就可以用自己的foreach宏定义来遍历元素了:
    std::string a;    CSharpCollection csc;    IEnumerable<std::string>& refcsc = csc;    foreach (a , refcsc ){        std::cout << a << std::endl;    }

  上面代码的第三行意在说明,如果一个类中继承了IEnumerable类,它一定是可迭代的,可以调用它的Reset()、MoveNext()、Current(),也可以用我们刚刚写的foreach来进行遍历。
0 0
原创粉丝点击