这个标题其实有点“标题党”的含义,因为C++在标准库中的实现迭代器的方式只有一种,也就是为类定义begin()和end()函数,C++11增加了range for语句,可以用来遍历迭代器中的元素。实现迭代器的第二种方式,就是用C++模拟C#和Java中的迭代器模式,并且我们可以定义出自己的foreach语句。除此之外,迭代器可能还有很多种实现的方法,各个库也会多自己的迭代器的实现有所定义,在这里只要明白迭代器的本质意义即可。
迭代器,也称作游标,是一种设计模式,我们可以对它进行递增(或选择下一个)来访问容器中的元素,而无需知道它内部是如何实现的。
很多语言提供foreach语句来访问容器中的每一个元素,其实也就是调用容器中的迭代器,抽象地来说就是:
foreach ( 元素 : 容器 ) { ... }
上面的代码等效于:
for ( 游标=获得迭代器的开头,获得迭代器的末尾; 游标 != 迭代器末尾; 游标移动一个单位 ) {...} // C++ 的迭代器模式
或者:
while ( 迭代器游标移动一个单位(返回是否存在下一个单位)) { ... } // C#、Java的迭代器模式,可以用迭代器.Current之类的方法返回游标所指向的元素
for ( auto __begin = collection.begin(), auto __end = collection.end(); __begin != __end(); ++__begin )
{ i = *__begin;
... //循环体
}#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);
}
}; CPPCollection cpc;
for (auto i : cpc){
std::cout << i << std::endl;
} 即可遍历集合中的所有元素了。#define interface struct
template <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 () { };
};#define foreach(item, collection) auto &__item_enumerator = collection.GetEnumerator(); __item_enumerator.Reset(); while (item = __item_enumerator.Current(), __item_enumerator.MoveNext())
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()内,当游标不可移动的时候,迭代器被删除。 std::string a;
CSharpCollection csc;
IEnumerable<std::string>& refcsc = csc;
foreach (a , refcsc ){
std::cout << a << std::endl;
}二、C++迭代器的两种实现方式 (Range for和C#、Java中的foreach),布布扣,bubuko.com
二、C++迭代器的两种实现方式 (Range for和C#、Java中的foreach)
原文地址:http://blog.csdn.net/froser/article/details/35274963