// Created by Frank M. Carrano and Tim Henry. // Copyright (c) 2013 __Pearson Education__. All rights reserved. /** Implementation file for the class ArrayBag: Recursive version. @file ArrayBag.cpp */ #include "ArrayBag.h" #include template ArrayBag::ArrayBag(): itemCount(0), maxItems(DEFAULT_CAPACITY) { } // end default constructor template int ArrayBag::getCurrentSize() const { return itemCount; } // end getCurrentSize template bool ArrayBag::isEmpty() const { return itemCount == 0; } // end isEmpty template bool ArrayBag::add(const ItemType& newEntry) { bool hasRoomToAdd = (itemCount < maxItems); if (hasRoomToAdd) { items[itemCount] = newEntry; itemCount++; } // end if return hasRoomToAdd; } // end add template bool ArrayBag::remove(const ItemType& anEntry) { int locatedIndex = getIndexOf(anEntry, 0); bool canRemoveItem = !isEmpty() && (locatedIndex > -1); if (canRemoveItem) { itemCount--; items[locatedIndex] = items[itemCount]; } // end if return canRemoveItem; } // end remove template void ArrayBag::clear() { itemCount = 0; } // end clear template bool ArrayBag::contains(const ItemType& anEntry) const { return getIndexOf(anEntry, 0) > -1; } // end contains template int ArrayBag::getFrequencyOf(const ItemType& anEntry) const { return countFrequency(anEntry, 0); } // end getFrequencyOf template vector ArrayBag::toVector() const { vector bagContents; for (int i = 0; i < itemCount; i++) bagContents.push_back(items[i]); return bagContents; } // end toVector // private template int ArrayBag::countFrequency(const ItemType& anEntry, int searchIndex) const { int frequency = 0; if (searchIndex < itemCount) { if (items[searchIndex] == anEntry) { frequency = 1 + countFrequency(anEntry, searchIndex + 1); } else { frequency = countFrequency(anEntry, searchIndex + 1); } // end if } // end if return frequency; } // end countFrequency // private template int ArrayBag::getIndexOf(const ItemType& target, int searchIndex) const { int result = -1; if (searchIndex < itemCount) { if (items[searchIndex] == target) { result = searchIndex; } else { result = getIndexOf(target, searchIndex + 1); } // end if } // end if return result; } // end getIndexOf