1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
/**
* Inserts an element, passed by parameter, into the 2-dimensional array. If
* necessary the array's capacity is changed in case the element is assigned to
* a row or column that doesn't exist yet. This method allows the insertion of
* an element in a specific position in the 2D array, which means that the row
* and column are also passed into the function as parameters. Note that this
* functions produces a simetric matrix, i.e., an element introduced into (a,b)
* will also be added to (b,a). In case the matrix already contains an element of
* the given type, that insertion will not occur.
* @param elem it's the reference to the element to be added to the 2D array
* @param row row where element is added
* @param col column where element is added
* @return true, in case the insertion is sucessful; false, otherwise
*/
template <class T>
bool Dyn2DArray<T>::insert(const T &elem, int row, int col){
/* checks whether row > col or col > row and assigns that value to maxTemp*/
int maxTemp;
if(row > col)
maxTemp = row;
else
maxTemp = col;
/* checks whether the 2D array has enough rows or cols for the new element */
if(maxTemp > cap){
/* stores the previous capacity of the vector */
int prevCap = cap;
/* array's new cap is maxTemp+1 */
cap = maxTemp + 1;
/* temporary array with new capacity */
T **newVec = new T *[cap];
for(int i = 0; i < cap; i++)
newVec[i] = new T[cap];
/* saving the content of the "smaller" array to the temporary array */
for(int i = 0; i < prevCap; i++)
for(int j = 0; j < prevCap; j++)
newVec[i][j] = vec[i][j];
/* releasing resources of the "smaller" array */
for(int i = 0; i < prevCap; i++)
delete [] vec[i];
delete [] vec;
/* assigning this "bigger" array to the original pointer */
vec = newVec;
}
/* adding the element to the given position, producing a simetric matrix is below */
/* pointer to new T, necessary to compare with un-initialized types */
T *blank = new T;
/* if the element in the given row/col is equal to a un-initialized type then the
insertion can proceed */
if((vec[row][col] == *blank) || (vec[col][row] == *blank)){
vec[row][col] = elem;
vec[col][row] = elem;
/* returns true to indicate sucessfull insertion */
return true;
}
else
/* returns false in case the insertion cannot occur, i.e., if there's already
an element in the given spot */
return false;
}
|