19.9.2.  The Subscript operator[]

[ fromfile: useroperators.xml id: None ]

Many lists and array-like classes offer an interface consistent with arrays, but with additional functionality. The subscript operator, operator[] is limited to a single parameter. It is usually used to provide index access to the elements of a container as you saw in Example 5.16. Example 19.14 defines a container class that has built-in protection against out-of-range array indices and that makes use of the subscript operator, operator[]().

Example 19.14. src/operators/vect1/vect1.h

[ . . . . ]
class Vect {
public:
    explicit Vect(int n = 10);
    ~Vect() {
        delete []m_P;
    }
    int& operator[](int i) {   1
        assert (i >= 0 && i < m_Size);
        return m_P[i];
    }
    int  ub() const {
        return (m_Size - 1);
    }                          2
private:
    int*  m_P;
    int   m_Size;
};

Vect::Vect(int n) : m_Size(n) {
    assert(n > 0);
    m_P = new int[m_Size];
}
[ . . . . ]

1

Access m_P[i].

2

Upper bound.

<include src="src/operators/vect1/vect1.h" href="src/operators/vect1/vect1.h" id="vect1h" mode="cpp"/>


The client code in Example 19.15 defines an array of Vect objects. This provides something similar to a matrix-like structure, where there is one fixed dimension and one that is possibly variable, or sparse, depending on the implementation details of Vect. main() also contains a simple right-justification method for numerical output.

Example 19.15. src/operators/vect1/vect1test.cpp

#include "vect1.h"

int main() {
    Vect a(60), b[20];

    b[1][5] = 7;
    cout << " 1 element 5 = "<< b[1][5] << endl;
    for (int i = 0; i <= a.ub(); ++i)
        a[i] = 2 * i + 1;
    for (int i = a.ub(); i >= 0; --i)
        cout << ((a[i] < 100) ? " " : "" )
        << ((a[i] < 10) ? " " : "" )
        << a[i]
        << ((i % 10) ? "  " : "\n");
    cout << endl;
    cout << "Now try to access an out-of-range index"
    << endl;
    cout << a[62] << endl;
}


<include src="src/operators/vect1/vect1test.cpp" href="src/operators/vect1/vect1test.cpp" id="vect1testcpp" mode="cpp"/>


Following is the output of the program.

src/operators/vect1> ./vect1
 1 element 5 = 7
119  117  115  113  111  109  107  105  103  101
 99   97   95   93   91   89   87   85   83   81
 79   77   75   73   71   69   67   65   63   61
 59   57   55   53   51   49   47   45   43   41
 39   37   35   33   31   29   27   25   23   21
 19   17   15   13   11    9    7    5    3    1

Now try to access an out-of-range index
vect1: vect1.h:16: int& Vect::operator[](int):
Assertion `i >= 0 && i < m_Size' failed.
Aborted
src/operators/vect1>