aboutsummaryrefslogtreecommitdiff
path: root/numericrange.h
blob: ebb20eff0c1d39afb1ec62671914d9b939491a4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#ifndef NUMERICRANGE_H
#define NUMERICRANGE_H

#include <iterator>
#include <stdexcept>

/*
 *  A (low memory usage) generator of ranges in steps of 1.
 */
template<typename T>
class NumericRange
{
public:
    class iterator
    {
        friend class NumericRange;
    public:
        typedef iterator self_type;
        typedef T value_type;
        typedef T& reference;
        typedef T* pointer;
        typedef std::bidirectional_iterator_tag iterator_category;
        typedef int difference_type;

        iterator(const T &first): m_value(first) {}

        T operator *() const { return m_value; }
        const iterator &operator ++() {
            ++m_value;
            return *this;
        }
        iterator operator++(int) {
            iterator copy(*this);
            ++m_value;
            return copy;
        }
        const iterator &operator --() {
            --m_value;
            return *this;
        }
        iterator operator--(int) {
            iterator copy(*this);
            --m_value;
            return copy;
        }

        bool operator ==(const iterator &other) const {
            return m_value == other.m_value;
        }
        bool operator !=(const iterator &other) const {
            return m_value != other.m_value;
        }

    private:
        T m_value;
    };

    /*
     * The range [first, last).
     */
    NumericRange(const T &first, const T &last)
        : m_begin(first)
        , m_end(last)
    {
        if (first > last) {
            throw std::logic_error("first > last");
        }
    }

    typedef const iterator const_iterator;

    iterator begin() const { return m_begin; }
    iterator end() const   { return m_end; }

    const_iterator cbegin() const { return m_begin; }
    const_iterator cend() const   { return m_end; }

private:
    iterator m_begin, m_end;
};

#endif // NUMERICRANGE_H