Ubiquitous Iterator (in English)

原创 2003年03月07日 08:43:00

Ubiquitous Iterator <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

This article is contributed by Wang HaiLong.

 

Preface

 

As one of 23 basic Design Patterns, Iterator seems to appear everywhere. This article discusses some scenarios where Iterator Pattern is applied, including STL, Collection in Java, IEnumXXXX interface in COM, IRowset interface in OLE DB, RecordSet Object in <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />ADO, ResultSet in JDBC, Cursor in Oracle's SQL/PL.

 

Iterator Concept

 

Iterator Pattern separates the iteration operation from Container/Collection. To satisfy Iterator Pattern, there must be two Objects: a Container and its Iterator.

The aim of Iterator Pattern is to unify the way of iterating a Container, in spite of what kiand of data is put in the Container, and how the Container's internal structure is implemented.

The following is a simple example imitating STL.

 

// SimpleArray.cpp

 

template<typename T>

class SimpleArray

{

T data[100];

 

public:

class Iterator

{

SimpleArray<T>* m_pArray;

int m_iCurrentIndex;

 

friend class SimpleArray<T>;

public:

Iterator( SimpleArray<T>* pArray = 0) : m_pArray(pArray)

{

}

 

void Reset()

{

m_iCurrentIndex = 0;

}

 

T operator *()

{

return m_pArray->data[m_iCurrentIndex];

}

 

void operator --()

{

m_iCurrentIndex--;

}

 

void operator ++()

{

m_iCurrentIndex++;

}

 

bool operator !=(const Iterator& another)

{

if( m_pArray != another.m_pArray )

return true;

 

if( m_iCurrentIndex != another.m_iCurrentIndex )

return true;

 

return false;

}

};

 

Iterator begin()

{

Iterator it(this);

it.m_iCurrentIndex = 0;

return it;

}

 

Iterator end()

{

Iterator it(this);

it.m_iCurrentIndex = 100;

return it;

}

 

friend class Iterator;

};

 

template<class Container>

int sum(Container & con)

{

Container::Iterator it;

int total = 0;

 

for( it = con.begin(); it != con.end(); it++)

{

total += *it;

}

 

return total;

}

 

void test()

{

SimpleArray<int> con;

 

int total = sum(con);

}

 

If later we don't want to use the SimpleArray any more, we can change the test function as below.

 

#include <set>

void test()

{

set<int> con;

 

int total = sum(con);

}

 

Hence the separation of data structure and algorithm.

 

STL

 

The above example demonstrates the usage of STL and how to write STL-style programs. Now lets discuss some STL features in more depth.

As we have seen, algorithms can exist independent of data structure using STL. The key concept is "Function Object", which is detailed in chapter 21 "STL Algorithms" of <<Thinking in C++>>.

Now lets take a glimpse of what is a "Function Object".

Take the method "sort" of list in STL, for example.

template<class Pred> void sort(greater<T> pr);

 

The parameter pr inherits the "Function Object" greater and is also a "Function Object".

And the implementation likely takes the following shape.

struct CCompareTwoItem : public std::greater< T >

{

public:

bool operator()( T item1, T item2 )

{

 

}

};

 

Iterator in Java and C++

 

Enumeration interface and Iterator interface( in Java2) are self-explanatory. What is more, sub view is supported in Java.

similar effect can be approximated through filter iterator.

IEnumXXXX interface in COM

The definition of IEnumXXXX is:

Interface IEnumXXX : IUnknown

{

virtual HRESULT Next(unsigned long celt, XXXX* rgelt, unsigned long * pceltFetched) = 0;

virtual HRESULT Skip(unsigned long celt) = 0;

virtual HRESULT Reset() = 0;

virtual HRESULT Clone(IEnumXXXX** ppeunm);

}

An good example is "Connectable Objects" in COM.

interface IConnectionPoint : IUnknown

{

HRESULT GetConnectionInterface(IID* pIID);

HRESULT GetConnectionPointContainer(IConnectionPointContainer** ppCPC);

HRESULT Advise(IUnknown* pUnk, DWORD* pdwCookie);

HRESULT Unadvise(DWORD dwCookie);

HRESULT EnumConnections(IenumConnections** ppEnum);

}

interface IconnectionPointContainer : IUnknown

{

HRESULT EnumConnectionPoints(IEnumConnectionPoints** ppEnum);

HRESULT FindConnectionPoint(REFIID riid, IConnectionPoint** ppCP);

}

interface IEnumConnectionPoints

{

HRESULT Next(ULONG cConnections, IConnectionPoint** rgpcn,ULONG* pcFetched);

HRESULT Skip(ULONG cConnections);

HRESULT Reset(void);

HRESULT Clone(IEnumConnectionPoints** ppEnum);

}

IConnectionPointContainer holds IConnectionPoint and IConnectionPointContainer's method EnumConnectionPoints returns an IEnumConnectionPoints which can iterate the IConnectionPointContainer to get every IConnectionPoint.

IRowset interface in OLE DB

IRowset method description:

AddRefRows Adds a reference count to an existing row handle.

GetData Retrieves data from the rowset's copy of the row.

GetNextRows Fetches rows sequentially, remembering the previous position.

ReleaseRows Releases rows.

RestartPosition Repositions the next fetch position to its initial position; that is, its position when the rowset was first created.

The definition of ICommand::Excute is:

HRESULT Execute (IUnknown* pUnkOuter, REFIID riid, DBPARAMS* pParams, LONG* pcRowsAffected, IUnknown** ppRowset);

This method returns an IRowset interface which can iterate through the result of "Excute".

RecordSet Object in ADO

The follow text is extracted from ADO help.

A Recordset object represents the entire set of records from a base table or the results of an executed command. At any time, the Recordset object only refers to a single record within the set as the current record.

Using the Open method on a Recordset object opens a cursor that represents records from a base table or the results of a query.

 

Ways to get RecordSet Object include:

On a Command object: Set recordset = command.Execute(RecordsAffected, Parameters, Options)

On a Connection object: Set recordset = connection.Execute(CommandText, RecordsAffected, Options)

ResultSet in JDBC

Connection Con = getConnection();

Statement stmt = con.createStatement(ResultSet.TYPE_SCROOL_INSENTIVE,

ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stmt.excuteQuery(query);

While(rs.next()){c};

Cursor in Oracle's SQL/PL

We can look on Cursor as a forward-only iterator.

 

Appendix

Some great books about Design Patterns:

<<Design Patterns>> by Zurich, Sydney, Urbana, Hawthorne;

<<Thinking in C++>> and <<Thinking in Java >> by Bruce Eckel;

<<The Design Patterns Java Companion>> by James W. Cooper.

 

WiGest: A Ubiquitous WiFi-based Gesture Recognition System

摘要 系统名为WiGest,该系统使用标准WiFi设备,没有修改,也没有训练数据,直接把接到的信号分为几个原语(primitives)。当使用单个AP的时候,探测原语准确度为87.5%,甚至是信号穿...
  • littleflypig
  • littleflypig
  • 2018年01月23日 22:00
  • 30

E - Ubiquitous Religions

A B C D E F E - Ubiquitous Religions Time Limit:5000MS     Memory Limit:65536KB     64bit IO F...
  • u013246297
  • u013246297
  • 2014年02月25日 20:19
  • 321

Ubiquitous Religions POJ2524

Ubiquitous Religions Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 15...
  • tiantangrenjian
  • tiantangrenjian
  • 2011年12月19日 16:33
  • 2509

POJ2524 Ubiquitous Religions —— 并查集

题目链接:http://poj.org/problem?id=2524 题解: 找出最多能有多少个不同的宗教,直接并查集就可以了。 第一次提交时没有注意到要输出“Case %d :”, 以后要注意...
  • DOLFAMINGO
  • DOLFAMINGO
  • 2017年03月24日 15:25
  • 111

《DianNao: A Small-Footprint High-Throughput Accelerator for Ubiquitous Machine-Learning》

1、DianNao项目介绍   中科院计算所的这几篇作为一个系列的论文进行阅读,在每一篇的论文阅读之前,我们先梳理一下寒武纪芯片DianNao的整体项目: 1.1、DianNao项目之前: ...
  • u013108511
  • u013108511
  • 2017年11月22日 16:16
  • 419

学习 effortless English 20天了

    已经学习 effortless English 20天了,要说有什么改变,我想最大的改变是:我已经开始自觉的带耳机了,耳朵听的也有一点点痛了!不能说已经有语感了,但没有刚开始听时那么烦了。  ...
  • lwbeyond
  • lwbeyond
  • 2011年06月27日 15:19
  • 6688

【转载】Android开发错误:Error:” ” is not translated in “en” (English) [MissingTranslation]如何处理?

转载请注明来源: http://blog.csdn.net/KjunChen/article/details/50043487 Android开发错误:Error:” ” is not transl...
  • lengqi0101
  • lengqi0101
  • 2017年05月11日 16:43
  • 599

English Self-Introduction

When you put youself in an English job interview, preparing a brief and impressive English Self-Intr...
  • DrifterJ
  • DrifterJ
  • 2012年08月20日 11:17
  • 5619

Error:(xx) Error: "xxxxxxx" is not translated in "en" (English)[MissingTranslation]

现象: Android导出APK包时出现,编译调试时不会出现。 错误信息: Error:(16) Error: "baidutieba_client_inavailable" is not tr...
  • sckoo
  • sckoo
  • 2015年05月04日 18:38
  • 4270

Error:(2) Error: "app_name" is not translated in "en" (English), "zh" (Chine

android多语言设置的时候预见的问题 解决方案android {... lintOptions{ checkReleaseBuilds false abo...
  • qq_28934205
  • qq_28934205
  • 2017年03月15日 10:10
  • 851
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Ubiquitous Iterator (in English)
举报原因:
原因补充:

(最多只允许输入30个字)