// Created by Frank M. Carrano and Tim Henry. // Copyright (c) 2013 __Pearson Education__. All rights reserved. /** Implementation file for the class ArrayBag. @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 /* // STUB template bool ArrayBag::remove(const ItemType& anEntry) { return false; // STUB } // end remove */ template bool ArrayBag::remove(const ItemType& anEntry) { int locatedIndex = getIndexOf(anEntry); bool canRemoveItem = !isEmpty() && (locatedIndex > -1); if (canRemoveItem) { itemCount--; items[locatedIndex] = items[itemCount]; } // end if return canRemoveItem; } // end remove /* // STUB template void ArrayBag::clear() { // STUB } // end clear */ template void ArrayBag::clear() { itemCount = 0; } // end clear template int ArrayBag::getFrequencyOf(const ItemType& anEntry) const { int frequency = 0; int curIndex = 0; // Current array index while (curIndex < itemCount) { if (items[curIndex] == anEntry) { frequency++; } // end if curIndex++; // Increment to next entry } // end while return frequency; } // end getFrequencyOf template bool ArrayBag::contains(const ItemType& anEntry) const { return getIndexOf(anEntry) > -1; } // end contains /* ALTERNATE 1: First version template bool ArrayBag::contains(const ItemType& target) const { return getFrequencyOf(target) > 0; } // end contains // ALTERNATE 2: Second version template bool ArrayBag::contains(const ItemType& anEntry) const { bool found = false; int curIndex = 0; // Current array index while (!found && (curIndex < itemCount)) { if (anEntry == items[curIndex]) { found = true; } // end if curIndex++; // Increment to next entry } // end while return found; } // end contains */ 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::getIndexOf(const ItemType& target) const { bool found = false; int result = -1; int searchIndex = 0; // If the bag is empty, itemCount is zero, so loop is skipped while (!found && (searchIndex < itemCount)) { if (items[searchIndex] == target) { found = true; result = searchIndex; } else { searchIndex++; } // end if } // end while return result; } // end getIndexOf