Bag  0.91
ArrayBag.cpp
Go to the documentation of this file.
1 //  Created by Frank M. Carrano and Timothy M. Henry.
2 //  Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.
3 
7 #include "ArrayBag.h"
8 #include <cstddef>
9 
10 template<class ItemType>
11 ArrayBag<ItemType>::ArrayBag(): itemCount(0), maxItems(DEFAULT_CAPACITY)
12 {
13 } // end default constructor
14 
15 template<class ItemType>
17 {
18  return itemCount;
19 } // end getCurrentSize
20 
21 template<class ItemType>
23 {
24  return itemCount == 0;
25 } // end isEmpty
26 
27 template<class ItemType>
28 bool ArrayBag<ItemType>::add(const ItemType& newEntry)
29 {
30  bool hasRoomToAdd = (itemCount < maxItems);
31  if (hasRoomToAdd)
32  {
33  items[itemCount] = newEntry;
34  itemCount++;
35  } // end if
36 
37  return hasRoomToAdd;
38 } // end add
39 
40 template<class ItemType>
41 bool ArrayBag<ItemType>::remove(const ItemType& anEntry)
42 {
43  int locatedIndex = getIndexOf(anEntry);
44  bool canRemoveItem = !isEmpty() && (locatedIndex > -1);
45  if (canRemoveItem)
46  {
47  itemCount--;
48  items[locatedIndex] = items[itemCount];
49  } // end if
50 
51  return canRemoveItem;
52 } // end remove
53 
54 template<class ItemType>
56 {
57  itemCount = 0;
58 } // end clear
59 
60 template<class ItemType>
61 int ArrayBag<ItemType>::getFrequencyOf(const ItemType& anEntry) const
62 {
63  int frequency = 0;
64  int curIndex = 0; // Current array index
65  while (curIndex < itemCount)
66  {
67  if (items[curIndex] == anEntry)
68  {
69  frequency++;
70  } // end if
71 
72  curIndex++; // Increment to next entry
73  } // end while
74 
75  return frequency;
76 } // end getFrequencyOf
77 
78 template<class ItemType>
79 bool ArrayBag<ItemType>::contains(const ItemType& anEntry) const
80 {
81  return getIndexOf(anEntry) > -1;
82 } // end contains
83 
84 template<class ItemType>
85 std::vector<ItemType> ArrayBag<ItemType>::toVector() const
86 {
87  std::vector<ItemType> bagContents;
88  for (int i = 0; i < itemCount; i++)
89  bagContents.push_back(items[i]);
90 
91  return bagContents;
92 } // end toVector
93 
94 // private
95 template<class ItemType>
96 int ArrayBag<ItemType>::getIndexOf(const ItemType& target) const
97 {
98  bool found = false;
99  int result = -1;
100  int searchIndex = 0;
101 
102  // If the bag is empty, itemCount is zero, so loop is skipped
103  while (!found && (searchIndex < itemCount))
104  {
105  if (items[searchIndex] == target)
106  {
107  found = true;
108  result = searchIndex;
109  }
110  else
111  {
112  searchIndex++;
113  } // end if
114  } // end while
115 
116  return result;
117 } // end getIndexOf