classRangeIter{private:intstep;intcur_val;public:RangeIter(intstep,intval):step(step),cur_val(val){}// these three methods form the basis of an iterator for use with a rangeIter-based for loop
booloperator!=(constRangeIter&other)const{if(step<0){returncur_val!=other.cur_val&&cur_val>other.cur_val;}returncur_val!=other.cur_val&&cur_val<other.cur_val;}// this method must be defined after the definition of IntVector since it needs to use it
intoperator*()const{returncur_val;}constRangeIter&operator++(){cur_val+=step;return*this;}};classRange{private:int_st,_end,_step;boolargs_check()const{if(_step==0){returnfalse;}if(_step<0&&_st<=_end){returnfalse;}return_step<=0||_st<_end;}public:Range(intstart,intend,intstep):_st(start),_end(end),_step(step){}Range(intstart,intend):_st(start),_end(end),_step(1){}explicitRange(intend):_st(0),_end(end),_step(1){}RangeIteriter(){returnRangeIter{_step,_st};}RangeItercbegin()const{if(!args_check()){throwstd::invalid_argument("step should match the exper start+n*step>end");}returnRangeIter{_step,_st};}RangeItercend()const{// if (!args_check()){
// throw std::invalid_argument("step should match the exper start+n*step>end");
// }
returnRangeIter{_step,_end};}RangeIterbegin(){if(!args_check()){throwstd::invalid_argument("step should match the exper start+n*step>end");}returnRangeIter{_step,_st};}RangeIterend(){returnRangeIter{_step,_end};}};
这里对 begin 做了参数检查,避免意外的错误情况,导致无限循环之类的情况,其实正常情况应该是把RangeIter 这个迭代器实现给塞到 private 域里面去,避免他人骚操作;但这里只是一个简单的演示demo就不用考虑太多;