Problem2019Final03List重载,引用

#pragma once
#include <list>
#include <memory>
#include <iostream>
using namespace std;

class MyList
{
private:
    std::shared_ptr< std::list<int> > pt; // a pointer to the real container
    std::list<int>::iterator left, right; // the position of slice is [left, right). 'left' is included, 'right' is excluded.

    std::list<int>::iterator forward(int pos) const{
        // count from 'left', find the element at position 'pos'.
        auto now = left;
        while(pos--) now++;
        return now;
    }
    
    std::list<int>::iterator backward(int pos) const{
        auto now = right;
        while (--pos) {
            now --;
        }
        return now;
    }

public:
    MyList(): pt(new std::list<int>()){
        left = pt->begin();
        right = pt->end();
        // Actually, left = right = pt->end(), because there is no element in the list.
    }
    
    MyList(std::shared_ptr< std::list<int> > p,std::list<int>::iterator l, std::list<int>::iterator r){
        pt = p;
        left = l;
        right = r;
    }
    
    MyList(const MyList& src){
        left = src.pt->begin();
        right = src.pt->end();
    }

//    MyList(const MyList& src, int a, int b){
//        left = src.forward(a);
//        right = src.backward(b);
//    }

    void append(int i){
        pt->insert(right, i);
        if(left==right){
            left=pt->begin();
            right=pt->end();
        }
        //insert i just before 'right'. 'right' and 'left' will be still valid (because we use list, not vector).
        // DEBUG !! Why I can't insert i??
    }

    int& operator[](int pos) const{
        return *forward(pos); // access the element at the 'pos'
    }

    ostream& output(std::ostream &out) const{
        out << "[";
        if (left != right){
            auto now = left;
            out << *now;
            now ++;
            for(; now != right; now++){
                out << "," << *now;
            }
        }
        out << "]";
        return out;
    }
    
    MyList operator()(int a, int b) const{
//        cerr<<"call operator()(int,int)const"<<endl;
        auto l = forward(a);
        auto r = forward(b);
        MyList list = MyList(this->pt,l,r);
        return list;
    }
    
    friend ostream& operator<<(ostream& out,const MyList& src);
};

ostream& operator<<(ostream& out,const MyList& src){
    return src.output(out);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。