CS代考计算机代写 /* seq.h

/* seq.h
*
* A structure to hold a sequence of elements.
*
* PUBLIC VARIABLES
*
* none!
*
* CONSTRUCTORS
*
* seq() Create an empty sequence
*
* PUBLIC FUNCTIONS
*
* add( x ) Add x to the end of the sequence
* remove() Remove the last element of the sequence
* remove( i ) Remove the i^{th} element of the sequence (expensive)
* shift( i ) Shift right everything starting at position i
* operator [i] Returns the i^{th} element (starting from 0)
* exists( x ) Return true if x exists in sequence, false otherwise
* clear() Deletes the whole sequence
* findIndex( x ) Find the index of element x, or -1 if it doesn’t exist
*/

#ifndef SEQ_H
#define SEQ_H

#include “headers.h”

#include
#include

using namespace std;

template class seq {

int storageSize;
int numElements;
T *data;

public:

seq() { // constructor
storageSize = 2;
numElements = 0;
data = new T[ storageSize ];
}

seq( int n ) { // constructor
storageSize = n;
numElements = 0;
data = new T[ storageSize ];
}

~seq() { // destructor
delete [] data;
}

seq( const seq & source ) { // copy constructor

storageSize = source.storageSize;
numElements = source.numElements;
data = new T[ storageSize ];
for (int i=0; i= numElements || i < 0) { cerr << "element: Tried to access an element beyond the range of the sequence: " << i << "(numElements = " << numElements << ")\n"; exit(-1); } return data[ i ]; } void clear() { delete [] data; storageSize = 1; numElements = 0; data = new T[ storageSize ]; } seq & operator = (const seq &source) { // assignment operator
storageSize = source.storageSize;
numElements = source.numElements;
delete [] data;
data = new T[ storageSize ];
for (int i=0; i
void
seq::add( const T &x )

{
// No storage left? If so, double the storage

if (numElements == storageSize) {
T *newData;

newData = new T[ storageSize * 2 ];
for (int i=0; i
void
seq::compress()

{
T *newData;

if (numElements == storageSize)
return;

newData = new T[ numElements ];
for (int i=0; i
bool
seq::exists( const T &x )

{
for (int i=0; i
int
seq::findIndex( const T &x )

{
for (int i=0; i
void
seq::shift( int i )

{
if (i < 0 || i >= numElements) {
cerr << "remove: Tried to shift element " << i << " from a sequence of " << numElements << " elements \n"; exit(-1); } if (numElements == storageSize) { T *newData; newData = new T[ storageSize * 2 ]; for (int i=0; ii; j–)
data[j] = data[j-1];

numElements++;
}

// Shift a suffix of the sequence to the left by one

template
void
seq::remove( int i )

{
if (i < 0 || i >= numElements) {
cerr << "remove: Tried to remove element " << i << " from a sequence of " << numElements << " elements \n"; exit(-1); } for (int j=i; j