A List Class Library for C++ - List(C++)

Element selection

The next group of operators allows access to arbitrary elements of Lists. The semantics of the subscript operator ([]) are the same as ordinary array subscripting except that you can't apply the address operator (&) to a subscript. The following are examples of the use of these operations:

   List<int> ix;
   for(int i = 0;i < 5;i++) {
   cout << ix;               // prints ( 0 1 2 3 4 )
   cout << (int) ix[3];      // prints 3
   ix[2] = -1;
   cout << ix;               // prints ( 0 1 -1 3 4 )
   int i = ix[4];            // i is 4
   int *ip = &ix[1];         // compile-time error
   cout << (int) ix[5];      // run-time error 

Operator []

L[n] is the n+1th of List L. (Remember that the first element of L is L[0].) The object returned will be converted automatically to a T anywhere that a T is expected, for example, T t = L[i];. In statements such as cout << L[i];, however, the user must cast it to a T, for example, cout << (T) L[i] ;. If the expression L[n] is the left operand of an assignment, then L is modified in the expected way.


L[i] = t replaces the i+1th element of List L with T t. It implements one type of element replacement for Lists (when L[n] is used as the left operand of =).

The arguments to these functions should always stay within the bounds of the List (in the range 0 through L.length() - 1). A statement such as T t = L[i] where i is out of bounds is considered a program bug, and the result may be unexpected. It is the application's responsibility to make sure that i is within the boundaries. (See "Error handling" below.) A statement such as L[i]=t where i is out of bounds has no effect on L.

A programmer should generally not use arbitrary access operations, for example, operator[](), to iterate over a List. Since Lists are linked, the implementation must generally step through the List to find a given element; thus, iterating this way is quadratic in the size of the List. The iterator class (to be introduced in the next section) should be used instead.

Next topic: Output
Previous topic: Unput

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005