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
|
#include <iostream>
#include <fstream>
using namespace std;
struct point {
double x;
double y;
};
//2. print out array content. Prameter: array
void Print_Array(point array[], int array_length)
{ for (int i=0; i<array_length; i++)
{ cout << array[i].x << ", " << array[i].y << '\n';
}
}
// copy all elements from previous array to new one
void copy_array (point * dest, point * src, int num_elements)
{ for (int j = 0; j < num_elements; j++)
{ dest[j].x = src[j].x;
dest[j].y = src[j].y;
}
}
// Reallocate the array
point * reallocate (point * pp, int num_elements, int & max_size)
{ max_size = max_size*2;
point *pp2 = new (nothrow) point[max_size];
copy_array (pp2, pp, num_elements);
delete [] pp;
return pp2;
}
point * add_element (point * pp, double x, double y, int & num_elements, int & max_size)
{ pp[num_elements].x = x;
pp[num_elements].y = y;
num_elements++;
if (num_elements >= max_size)
pp = reallocate (pp, num_elements, max_size);
return pp;
}
int main()
{ int max_size = 10;
int num_elements = 0;
double x,y;
ifstream infile;
infile.open("datainput.txt");
point *pp;
pp = new (nothrow) point[max_size];
while (infile >> x >> y)
pp = add_element (pp, x, y, num_elements, max_size);
Print_Array (pp, num_elements);
delete [] pp;
system ("pause");
return 0;
}
|