c++ 自己实现一个迭代器

具体代码

/*
    自定义迭代器的实现
*/
#include <iostream>
using namespace std;
class num
{
    int val;    //具体的数字
    int length; //数字的位数
    void calculate_length(){
        if(val/10==0){      //这个数字只有1位
            length=1;
            return;
        }
        int x=10;           //这里就是不断重复除直到为0,从而得出数字的具体位数
        int pow=0;
        int tempNum=val;
        while(tempNum!=0){
            tempNum/=10;
            pow++;
        }
        length=pow;
    }
public:
    num(int tempNum)
    { //以下是一些基本的函数,用于设置值
        val=tempNum;
        calculate_length();
    }
    void set(int tempNum)
    {
        val = tempNum;
        calculate_length();
    }
    int get()
    {
        return val;
    }
    //以下是迭代器的部分
    class iterator
    {
        int pos;    //数字的下标
        num* obj;   //如果要在迭代器里面访问num的内容,必须要这个
    public:
        /*
            迭代器,要重载*,++,--
        */
        iterator(num* ptr,int n)
        {
            pos = n;
            obj = ptr;
        }
        iterator()
        {
            //空构造器
            pos = 0;
            obj = nullptr;
        }
        //操作符
        void operator++(){  //注意,这种没有参数的++重载的是前置的++   ++it
            pos++;
        }
        void operator++(int i){  //这种有任意int参数的重载的是后缀++  it++
            pos++;
        }
        void operator--(){
            pos--;
        }
        void operator--(int i){  
            pos--;
        }
        int operator*()const{
            //13324 取第二位10位:  (13324%100)/10
            //num  去除第n位     (num % 10^(n))/ 10^(n-1)
            if(pos>=obj->length) return -1;
            if(pos==0)return obj->val%10;
 
            int o=10;
            int pow=0;
            while(pow<(pos-1)){
               // cout<<pow<<" "<<pos<<endl;
                o*=10;
                pow++;
            }
            return (obj->val%(o*10))/(o);
        }
        bool operator!=(const iterator& it){
            return it.pos!=pos;
        }
        bool operator==(const iterator& it){
            return it.pos==pos;
        }
    };
    //获取迭代器,常见的比如begin,end;
    iterator begin()
    {
        return iterator(this,0);
    }
    iterator end()
    {
        return iterator(this,length);
    }
};
int main()
{
    num a(2354862);
    for(auto it=a.begin();it!=a.end();it++){
        cout<<*it<<" ";
    }
    cout<<endl;
    
    return 0;
}

参考资料

https://blog.csdn.net/dyyzlzc/article/details/103336232

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值