c++ STL Iterator模拟

C++  STL中的Iterator遍历容器的时候,无需知道具体的是哪个容器,只用传入地址即可。容器可以使用数组来模拟。

代码如下:

/************************************************************************/
/* implement of find function without stl                               */
/************************************************************************/
#include <iostream>
using namespace std;
//we do not need to modify the value here
typedef const int* IteratorType;
IteratorType find(IteratorType begin,IteratorType end,const int & Value);
int main()
{
    const int count = 100;
    int aContainer[count];
    IteratorType begin = aContainer;
    IteratorType end = aContainer+count;
    for (int i=0;i<count;i++)
    {
        aContainer[i] = i*2;
    }
    int Number = 0;
    while (Number != -1)
    {
        cout<<"Please Input a Number(-1 = end):";
        cin>>Number;
        if (Number != -1)
        {
            IteratorType pos = find(begin,end,Number);
            if (pos != end)
            {
                cout<<"Find at position:"<<pos-begin<<endl;
            }
            else
            {
                cout<<"not found!"<<endl;
            }
        }
    }
}
IteratorType find(IteratorType begin,IteratorType end,const int & Value)
{
    while (begin != end && *begin != Value)
    {
        ++begin;
    }
    return begin;
}

在这个例子中find函数无需知道容器acontainer的具体细节。

posted @ 2013-01-16 17:30  理想空间  阅读(395)  评论(0编辑  收藏  举报