grow function to change size of array class
hi there y'all. I am study c++ and am trying to write a method to increase
the size of an array when passed an int value determing the array size. This
is my go at it which does not work. Can anybody give me some idea how to do
this?? Thanks for your time :)
template <class BType, class IType>
void Array<BType, IType>::grow(int newS)
{
arrayData = new BType[newS];
assert (arrayData != 0);
for (int i = 0; i <= hibnd - lobnd; ++i)
arrayData[i] = BType[i];
}
inheriting the array class to matrix class
Thanks for the help. I still am finding it hard to understand a couple of
things about this code.
This was the code I wrote and it worked.
BType * newValues = new BType[newS];
for (int i = 0; i < newS; ++i)
newValues[i] = arrayData[i]; // copy old array
delete [ ] arrayData; // delete the old array
arrayData = newValues;
...all good. The next thing in the exercise we are instructed to do is
create a matrix using two arrays from our array class. :
template <class BType, class IType1 = int, class IType2 = int>
class Matrix{
private:
IType1 lobnd1, hibnd1;
IType2 lobnd2, hibnd2;
Array<BType, IType2>* *MData; // this is clearer than Array<...> **MData
bool outOfRange(IType1) const;
public:
Matrix(int, int, IType1 = 0, IType2 = 0); // constructor
Matrix(const Matrix<BType, IType1, IType2> &); // copy constructor
~Matrix(); // destructor
Array<BType, IType2>& operator[](IType1); // 1st [] operator
Array<BType, IType2>& operator[](IType1) const; // ... and again
Matrix& operator= (const Matrix<BType, IType1, IType2> &); // = operator
void addCol(int = 1); // increase row length
void addRow(int = 1); // increase column length
void grow(int = 0, int = 0); // change size
IType1 lo1() const; // inline functions
IType1 hi1() const;
IType2 lo2() const;
IType2 hi2() const;
};
template <class BType, class IType1, class IType2>
Matrix<BType, IType1, IType2>::Matrix(int SZ1, int SZ2, IType1 l1, IType2
l2)
: lobnd1(l1), hibnd1(l1 + SZ1 - 1), lobnd2(l2), hibnd2(l2 + SZ2 - 1)
{
MData = new Array<BType, IType2>*[SZ1];
assert(MData != 0);
for (IType1 i = 0; i < hibnd1 + 1 - lobnd1; ++i)
{
MData[i] = new Array<BType, IType2>(SZ2, l2);
assert(MData[i] != 0);
}
}
the thing then is we have to write the functions, addCol, addRow, and grow.
I thought armed with my knowledge from the first exercise that it would be
something like this:::
template <class BType, class IType1, class IType2>
void Matrix<BType, IType1, IType2>::addCol(int newC)
{
BType * newCols = new BType[hibnd1+newC];
for (int i = 0; i < newC; ++i)
newCols[i] = MData[i];
delete [] MData;
MData = newCols;
}
-- but I am somewhat confused. Thinking it through what I want to do is
change the size of the arrays created from array.h,
Thanks for your help
Santos