Array indexing starting at a number not 0

后端 未结 13 2118
Happy的楠姐
Happy的楠姐 2021-02-20 04:02

Is it possible to start an array at an index not zero...I.E. you have an array a[35], of 35 elements, now I want to index at say starting 100, so the numbers would be a[100], a[

13条回答
  •  我寻月下人不归
    2021-02-20 04:36

    C++ provides quite a bit more than C in this respect. You can overload operator[] to do the subtraction, and if you want report an error (e.g., throw an exception) if the subscript is out of range.

    As a minimal demo, consider the following:

    #include 
    #include 
    
    template 
    class array {
        T data[upper-lower];
    public:
        T &operator[](int index) { 
            if (index < lower || index >= upper)
                throw std::range_error("Index out of range");
            return data[index-lower]; 
        }
        T *begin() { return data; }
        T *end() { return data + (upper-lower); }
    };
    
    int main() {
        array data;
    
        for (int i=-3; i<5; i++)
            data[i] = i;
    
        for (auto const &i : data) 
            std::cout << i << "\t";
        std::cout << "\n";
    }
    

提交回复
热议问题