#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);
}
Problem2019Final03List重载,引用
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...