-
Notifications
You must be signed in to change notification settings - Fork 0
Collection Class
A container that stores a set of unique double values in a dynamically allocated array. The array grows by one when I add a number and shrinks by one when I remove one. Duplicates are rejected on add.
Source files: collection/collection.hpp, collection/collection.cpp, collection/userInput.cpp.
-
addNumber(double)adds a value if it is not already present. It allocates a new array one slot larger, copies the old values, appends the new value, and replaces the old array. -
removeNumber(double)deletes a value if present. It allocates a new array, copies every element except the matched one, shifting later elements down, and replaces the old array. -
check(double)returns the index of a value or-1if it is absent. -
value()returns the sum of all elements. -
output()prints the elements separated by spaces. -
size()returns the element count.
The class manages its own heap memory, so it defines the copy constructor, the assignment operator, and the destructor. The copy constructor and assignment both allocate a fresh array and deep-copy the elements, so two collections never share the same buffer. Assignment guards against self-assignment before freeing its array.
classDiagram
class Collection {
-double* col_
-int size_
+Collection()
+Collection(const Collection&)
+operator=(const Collection&) Collection&
+~Collection()
+size() int
+check(double) int
+addNumber(double) void
+removeNumber(double) void
+output() void
+value() double
}
col_ points at the heap array. size_ tracks how many doubles it holds. A default-constructed collection starts empty with a null pointer.
userInput.cpp runs a small loop. It reads a command and, for add or remove, a number:
-
a <number>adds the number. If it is already present, it printsduplicate!. -
r <number>removes the number. If it is absent, it printsnot present!. - anything else quits.
After each successful add or remove it prints the current contents and the running total.
enter operation [a/r/q] and number: a 4
your numbers: 4 , total value: 4
enter operation [a/r/q] and number: a 6
your numbers: 4 6 , total value: 10
enter operation [a/r/q] and number: a 4
duplicate!
enter operation [a/r/q] and number: r 4
your numbers: 6 , total value: 6
enter operation [a/r/q] and number: q
g++ -std=c++11 collection/*.cpp -o collection
./collectionaddNumber and removeNumber free the old buffer with delete rather than delete[], which is the wrong form for an array allocated with new[]. removeNumber also allocates size_ + 1 slots when it only needs size_ - 1. The class works for the lab's inputs, and these are noted on the Roadmap page.