Bag ADT: Abstract Data Types in C++ – 2
February 13, 2011 Leave a comment
We continue our discussion of the Bag ADT.
We first look at the implementation of the insert function.
(All function implementations are part of an implementation file, bag.cpp, in which, among other header files, “bag.h” is included.)
The insert function : bool insert (const Item& myItem); works as follows:
– it inserts the argument, myItem into the “data” array if there is space for insertion into the array, i.e. if size( ) < CAPACITY.
– In that case, it inserts myItem at index “used” in the array, and returns true.
– Otherwise, (i.e. if there is no space for insertion) it returns false.
bool Bag :: insert ( const Item& myItem)
if ( size ( ) >= CAPACITY)
data[used] = myItem;
Note that we pass the argument myItem by reference. Passing by reference helps to optimize on memory in case the argument is of a large size. Further, by passing it as a const reference, we ensure that what we are passing does not get accidentally modified.