The following is the header file for Deque.cpp:
Code:
#ifndef DEQUE_H
#define DEQUE_H
#include <iostream>
using namespace std;
typedef int Item_type;
class Deque
{
public:
Deque();
Deque( const Deque& other );
~Deque();
void add( const Item_type& item, bool leftEnd = false );
Item_type remove( bool leftEnd = true );
bool empty() const;
int size() const;
Deque& operator=( const Deque& other );
void print( bool verbose = false ) const;
private:
static const int CAPACITY = 10; // Initial number of items allowed
static const float GROWTH; // Growth factor to expand data
int maxCount; // Size of the array
int count; // Number of values currently in the Deque
int front; // First used entry in the array
Item_type* data; // Dynamic array of values in the Deque
void copy( const Deque& other );
void clear();
void grow();
};
Deque operator+( const Deque& left, const Deque& right );
bool operator==( const Deque& left, const Deque& right );
#endif
And this is a piece of Deque.cpp (definition file):
Code:
#include <iostream>
#include <iomanip>
#include "Deque.h"
using namespace std;
const float Deque::GROWTH = 1.5;
Deque::Deque()
// A new Deque is created with no items in it.
{
count = 0;
front = 0;
maxCount = CAPACITY;
data = new Item_type[maxCount];
}
... some function definitions ...
void Deque::add( const Item_type& item, bool leftEnd )
{
if (count>=maxCount) grow();
... some code here ...
}
... some function definitions ...
void Deque::grow()
// Grow helper function
// The array is enlarged with it entries copied to the new array
{
Item_type* temp;
int old_maxCount = maxCount;
maxCount = maxCount + int(GROWTH*maxCount);
temp = new Item_type[ maxCount ];
for ( int i = front; i < ((front+count)%old_maxCount); i++ ){
temp[ i ] = data[ i ];
}
delete [] data;
data = temp;
}
So as you may guess when add() is invoked it checks to see if the Deque needs to be enlarged. If so then executes grow(), then adds the entry and counts up (which are not included in the above).
The problem is that grow() doesn't work properly. This is what it outs when the array has a size of 40:
Code:
============================================
Deque has 40 entries.
[ 0]= 0 [ 1]= 0 [ 2]= 0 [ 3]= 0 [ 4]= 0
[ 5]= 0 [ 6]= 0 [ 7]= 0 [ 8]= 0 [ 9]= 0
[10]= 0 [11]= 0 [12]= 0 [13]= 0 [14]= 0
[15]= 0 [16]= 0 [17]= 0 [18]= 0 [19]= 0
[20]= 0 [21]= 0 [22]= 0 [23]= 0 [24]= 0
[25]=126 [26]=127 [27]=128 [28]=129 [29]=130
[30]=131 [31]=132 [32]=133 [33]=134 [34]=135
[35]=136 [36]=137 [37]=138 [38]=139 [39]=140
============================================
The instruction that created the above is:
Code:
Deque A;
for (int i=0; i<40; i++) A.add( 101+i );
All advises are greatly appreciated.