/* IntList.cpp * Anthony Larrain * * Represents an integer vector */ #include #include #include #include #include using namespace std; class IntList { private: int cap; int cardinality; int *buffer; void grow(); // prohibit pass by value and // copy initialization IntList(IntList &); public: IntList() : cap(10), cardinality(0), buffer(new int[cap]) {} ~IntList(); // add an element to the end of the list. void push_back(int number); // number of integers in the list int size() const; // capacity of the array int capacity() const; // returns true if list is empty, else false int empty() const; // returns a reference to the element at index i. // for now we assume a valid index is entered. int &at(int i); // return the list as a string string toString() const; }; int main(int argc, char *argv[]) { srand(time(NULL)); IntList list; for(int i = 0; i < 20 ; i++){ list.push_back(rand() % 1000); } cout << list.size() << endl; cout << list.toString() << endl; cout << list.at(0) << endl; list.at(0) = 100000; cout << list.at(0) << endl; /* wont work, copy constructor is private */ /* IntList list2(list); */ system("PAUSE"); return EXIT_SUCCESS; } IntList::~IntList(){ delete [] buffer; } void IntList::grow(){ int *backUp = buffer; cap *= 2; buffer = new int[cap]; for(int i = 0; i < size(); i++){ buffer[i] = backUp[i]; } delete [] backUp; } void IntList::push_back(int number){ if(size() == capacity()){ grow(); } buffer[cardinality++] = number; } int IntList::size() const { return cardinality; } int IntList::capacity() const { return cap; } int IntList::empty() const { return size() == 0; } int & IntList::at(int i) { return buffer[i]; } string IntList::toString() const { ostringstream os; for(int i = 0; i < size(); ++i){ os << buffer[i] << ' '; } return os.str(); }