Is there a range class in C++11 for use with range based for loops?

前端 未结 8 1292
失恋的感觉
失恋的感觉 2020-11-27 11:33

I found myself writing this just a bit ago:

template 
class range_class {
 public:
   class iterator {
      friend c         


        
8条回答
  •  旧巷少年郎
    2020-11-27 11:42

    This might be a little late but I just saw this question and I've been using this class for a while now :

    #include 
    #include 
    #include 
    
    template struct Range final {
        struct Iterator final{
            T value;
            Iterator(const T & v) : value(v) {}
            const Iterator & operator++() { reverse ? --value : ++value; return *this; }
            bool operator!=(const Iterator & o) { return o.value != value; }
            T operator*() const { return value; }
        };
        T begin_, end_;
        Range(const T & b, const T & e)  : begin_(b), end_(e) {
            if(b > e) throw std::out_of_range("begin > end");
        }
    
        Iterator begin() const { return reverse ? end_ -1 : begin_; }
        Iterator end() const { return reverse ? begin_ - 1: end_; }
    
        Range() = delete;
        Range(const Range &) = delete;
    };
    
    using UIntRange = Range;
    using RUIntRange = Range;
    

    Usage :

    int main() {
        std::cout << "Reverse : ";
        for(auto i : RUIntRange(0, 10)) std::cout << i << ' ';
        std::cout << std::endl << "Normal : ";
        for(auto i : UIntRange(0u, 10u)) std::cout << i << ' ';
        std::cout << std::endl;
    }
    

提交回复
热议问题