zoukankan      html  css  js  c++  java
  • 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的具体细节。

  • 相关阅读:
    组合数据类型练习
    实验四、递归下降语法分析实验
    词法分析实验报告
    Python基础综合练习
    大数据概述
    一个词法分析程序
    linux基本命令
    有限自动机的构造与识别
    我对编译原理的小小了解
    Scrum 冲刺博客 2
  • 原文地址:https://www.cnblogs.com/jianboqi/p/2863128.html
Copyright © 2011-2022 走看看