Vector 2: Slicing

In this version, we add a slicing operator. The slicing operator constructs a new vector that shares data elements with the original vector, but has a limited range of indexes.

//
// Vector2.C 
//
// A. B. Maccabe  3/10/97
//
// A simple vector class -- illustrates overloading the index operator
//    with array bounds checking
//
//
// this example adds the ability to take a slice from the vector.
//


#include <assert.h>
#include <iostream.h>

class Vector {
public:
    // constructor
    Vector( int lower, int upper ) {
	lb = lower;
	ub = upper;
	data = new double[upper-lower+1];
    };

    double& operator[] ( int indx ) {
	assert( lb<=indx && indx<=ub );
	
	return data[indx-lb];
    };

    friend ostream& operator << ( ostream &os, Vector v ) {
	for( int i = v.lb ; i <= v.ub ; i++ ) {
	    os << i << ':' << v.data[i-v.lb] << ' ';
	}
	return os;
    }
    

    Vector slice( int lower, int upper ) {
	assert( lower<=upper && lb<=lower && upper<=ub );
	return Vector( &data[lower-lb], lower, upper );
    };

 
private:
    // private constructor
    Vector( double *dat, int lower, int upper ) {
	data = dat;
	lb = lower;
	ub = upper;
    };

    int lb, ub;
    double *data;
};

int main() {
    Vector v( 10, 20 );

    for( int i = 10 ; i <= 20 ; i++ ) {
	v[i] = i;
    }

    cout << v << endl;

    // construct a simple slice
    Vector v2 = v.slice( 15, 18 );
    cout << v2 << endl;

    v2[16] = -16;
    cout << v << endl;

    // now, take a slice of a slice
    Vector v3 = v2.slice( 16, 17 );
    cout << v3 << endl;

    v3[17] = -17;
    cout << v << endl;
}

Barney Maccabe
Last modified: Wed Apr 2 17:48:13 MST