This program implements a few vector methods for Example: floatVector - Version 1.
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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
// fv1/floatVector.cpp implements some of the floatVector methods // Fred Swartz 2004-12-01 #include <cstdlib> using namespace std; #include "floatVector.h" //====================================================== constructor floatVector::floatVector() { _capacity = 0; _size = 0; _data = NULL; }//end constructor //======================================================= destructor // free space allocated for the array floatVector::~floatVector() { delete [] _data; } //=============================================================== at // Return element at given position. float& floatVector::at(int position) const { return _data[position]; } //============================================================= back // Return reference to last element. float& floatVector::back() const { return _data[_size-1]; } //========================================================= capacity // Return the current storage capacity. int floatVector::capacity() const { return _capacity; } //======================================================== push_back // Add item to end of the vector, expand if necessary. void floatVector::push_back(float item) { if (_capacity <= _size) { // Start with capacity for 10 elements. // Expand by doubling each time. reserve(_capacity>0 ? 2*_capacity : 10); } _data[_size] = item; _size++; } //============================================================= size // Return number of data elements. int floatVector::size() const { return _size; } //============================================================ clear // Remove all data. For floats this is as simple // as resetting the size. It would also be possible // to delete the allocated memory, but the memory // is left as it is in anticipation of being used again. void floatVector::clear() { _size = 0; } //========================================================== reserve // Insure requested capacity. void floatVector::reserve(int cap) { if (cap > _capacity) { // This requires an expansion. float *new_data = new float[cap]; // allo new array. if (_capacity > 0) { // There is a previous allocation to copy and delete. for (int i=0; i<_size; i++) { new_data[i] = _data[i]; } delete [] _data; // Deallocate old array. } _capacity = cap; // Set new capacity. _data = new_data; // Point to new array. } } |