Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Руководство программиста_администратора.docx
Скачиваний:
2
Добавлен:
01.07.2025
Размер:
551.89 Кб
Скачать

6. Приложение b. Использование динамического массива.

#include <iostream>

using namespace std;

template <typename type>

class TArray : public ts::TExtData {

type *arr;

public:

TArray() : arr(NULL) {}

void resize(int sz) {

int curSz = size();

if (curSz < sz) {

type* curArr = arr;

type* curData = (type*)*this;

arr = new type[sz];

if (curData) memcpy(arr,curData,curSz*sizeof(type));

if (curArr) delete [] curArr;

}

extDataSize() = sz*sizeof(type);

}

operator const type* () const { return arr ? arr : (type*)extData(); }

operator type* () { return arr ? arr : (type*)extData(); }

type& operator [] (int i) { return *(((type*)*this)+i); }

int size() {return extDataSize() / sizeof(type);}

~TArray() {

if (arr) delete[] arr;

}

TArray (const TArray<type>& t) : arr(NULL) {

memcpy(extData(),(const type*)t,extDataSize());

}

};

tfun int tGranula(tval TArray<int> tArr){

TArray<int> &arr = (TArray<int>&)tArr;

int res = 0;

for( int i = 0; i < arr.size(); i++ ){

res += arr[ i ];

cout << ts::myRank << ": " << arr[i] << endl;

}

cout << endl;

return res;

}

tfun int main (int argc, char *argv[]) {

tval TArray<int> tArr;

TArray<int> &arr = (TArray<int>&)tArr;

int res;

arr.resize(10);

for (int i = 0; i < arr.size(); i++) {

arr[i] = i;

}

res = tGranula(tArr);

arr.resize(15);

res = tGranula(tArr);

arr.resize(5);

res = tGranula(tArr);

arr.resize(15);

res = tGranula(tArr);

cout << endl << "Result = " << res << endl << endl;

return 0;

}