aboutsummaryrefslogtreecommitdiffstats
path: root/C++/DynamicArray.cpp
diff options
context:
space:
mode:
authorzedarider <ymherklotz@gmail.com>2016-02-26 21:15:09 +0000
committerzedarider <ymherklotz@gmail.com>2016-02-26 21:15:09 +0000
commitf7a1296d353dea1f98b47d4baef87426ceadf6b5 (patch)
treec4fc565b3e2f672647033d639601f695782f1562 /C++/DynamicArray.cpp
parentc2d76b36f9f2ef70de599add53c08a38af3d1760 (diff)
downloadimperial_2015-f7a1296d353dea1f98b47d4baef87426ceadf6b5.tar.gz
imperial_2015-f7a1296d353dea1f98b47d4baef87426ceadf6b5.zip
Organising into folders
Diffstat (limited to 'C++/DynamicArray.cpp')
-rw-r--r--C++/DynamicArray.cpp78
1 files changed, 78 insertions, 0 deletions
diff --git a/C++/DynamicArray.cpp b/C++/DynamicArray.cpp
new file mode 100644
index 0000000..4875109
--- /dev/null
+++ b/C++/DynamicArray.cpp
@@ -0,0 +1,78 @@
+#include <iostream>
+#include <fstream>
+#include <cstdlib>
+#include <string>
+
+using namespace std;
+
+// point object structure
+struct point {
+ double x, y;
+
+ void p_str() {
+ cout << "(" << x << ", " << y << ")" << endl;
+ }
+};
+
+// declaration of method
+void readPoints(string, int&, int&, point*&);
+
+int main() {
+ string fileLocation = "./PointFile.txt";
+ // declares the size and capacity of the array which both have to be tracked and initialises them
+ int size = 0;
+ int capacity = 1;
+ point* pArray = new point[capacity];
+ readPoints(fileLocation, capacity, size, pArray);
+
+ // prints out the content of the array
+ for(int i = 0; i < size; i++) {
+ pArray[i].p_str();
+ }
+
+ // prints out the characteristics of the array
+ cout << "array capacity:\t\t" << capacity << endl << "array size:\t\t" << size << endl << "array physical size:\t" << size*sizeof(point) << " bits\t=\t" << size*sizeof(point)/8 << " bytes" << endl;
+
+ delete[] pArray;
+ return 0;
+}
+
+// method that creates the array
+void readPoints(string fileloc, int &cpcty, int &sz, point* &pa) {
+ // declares file and other variables
+ ifstream pointFile;
+ point tmpp;
+
+ pointFile.open(fileloc);
+
+ // Error opening file
+ if(!pointFile.is_open()) {
+ cout << "couldn't open input file" << endl;
+ exit(EXIT_FAILURE);
+ }
+
+ // reads the two points from the file
+ while(pointFile >> tmpp.x >> tmpp.y) {
+ // increases the sz of the array
+ sz++;
+ // checks if the array is still large enough for the element
+ if(sz <= cpcty) {
+ // adds point to the end of the array
+ pa[sz-1] = tmpp;
+ } else {
+ // if array isn't large enough creates new dynamic array
+ // of two times the sz
+ point* tmpa = new point[cpcty*=2];
+ for(int i = 0; i < sz; i++) {
+ tmpa[i] = pa[i];
+ }
+ // never have to delete the tmpa as it points to the new pa
+ tmpa[sz-1] = tmpp;
+ // delete old pa
+ delete[] pa;
+ pa = tmpa;
+ }
+ }
+
+ pointFile.close();
+} \ No newline at end of file