版本比较
如何在 C++ 中像 Python 一样写 for 循环
正文
增加 8 行删除 1 行
10 行未改动11121314151516171850 行未改动69707172737475767778798010 行未改动#define for(x) for(auto x)
template<class T>class Range{private: T start_,stop_,step_;public: Range(T stop):start_(0),stop_(stop),step_(1){ if (stop_<start_) stop_=start_;50 行未改动}```
的代码,删除了原版 C++ 的 for 循环写法,与 Python 保持一致。
压行版:
```cpp#define in :#define for(x) for(auto x)template<class T>class Range{T start_,stop_,step_;public:Range(T stop):start_(0),stop_(stop),step_(1){if(stop_<start_)stop_=start_;}Range(T start,T stop):start_(start),stop_(stop),step_(1){if(stop_<start_)stop_=start_;}Range(T start,T stop,T step):start_(start),stop_(stop),step_(step){if(step_==0)throw std::invalid_argument("range() step must not be zero");if((step_>0 and stop_<start_)or(step_<0 and stop_>start_))stop_=start_;}template<class _T>class iterator{_T value_,step_;public:iterator(_T value,_T step):value_(value),step_(step){}_T operator*()const{return value_;}iterator&operator++(){value_+=step_;return*this;}iterator operator++(int){iterator t=*this;++(*this);return t;}bool operator==(const iterator&other)const{if(step_>0)return value_>=other.value_;else return value_<=other.value_;}bool operator!=(const iterator&other)const{return not(*this==other);}};iterator<T>begin()const{return iterator<T>(start_,step_);}iterator<T>end()const{return iterator<T>(stop_,step_);}};template<class T>inline Range<T>range(T stop){return Range(stop);}template<class T>inline Range<T>range(T start,T stop){return Range(start,stop);}template<class T>inline Range<T>range(T start,T stop,T step){return Range(start,stop,step);}```