Question

In: Computer Science

C++ Create an ArrayBag template class from scratch. This will require you to create two files:...

C++

Create an ArrayBag template class from scratch. This will require you to create two files: ArrayBag.hpp for the interface and ArrayBag.cpp for the implementation.

The ArrayBag class must contain the following protected members:

static const int DEFAULT_CAPACITY = 200;  // max size of items_ 
ItemType items_[DEFAULT_CAPACITY];        // items in the array bag
int item_count_;                   // Current count of items in bag

/**
   @param target to be found in items_
   @return either the index target in the array items_ or -1,
   if the array does not containthe target.
**/
int getIndexOf(const ItemType &target) const;

Your ArrayBag class must contain the following public members:

/** 
   Default Constructor
   item_count_  <- 0
**/
ArrayBag();

/**
   @return item_count_ : the current size of the bag
**/
int getCurrentSize() const;

/**
   @return true if item_count_ == 0, false otherwise
**/
bool isEmpty() const;

/**
   @return true if new_entry was successfully added to items_, 
                                                 false otherwise
**/
bool add(const ItemType &new_entry);

/**
   @return true if an_entry was successfully removed from items_, 
                                                 false otherwise
**/
bool remove(const ItemType &an_entry);

/**
   @post item_count_ == 0
**/
void clear();

/**
   @return true if an_entry is found in items_, false otherwise
   -> THIS METHOD MUST CALL getIndexOf() <-
**/
bool contains(const ItemType &an_entry) const;

/**
   @return the number of times an_entry appears in items_
**/
int getFrequencyOf(const ItemType &an_entry) const;

Solutions

Expert Solution

// ArrayBag.hpp

#ifndef ARRAYBAG_HPP
#define ARRAYBAG_HPP


template<class ItemType>
class ArrayBag {
protected:
  
   static const int DEFAULT_CAPACITY = 200; // max size of items
   ItemType items_[DEFAULT_CAPACITY]; // items in the array bag
   int item_count_; // Current count of items in bag

   /**
   @param target to be found in items_
   @return either the index target in the array items_ or -1,
   if the array does not containthe target.
   **/
   int getIndexOf(const ItemType& target) const;

public:

   /**
   Default Constructor
   item_count_ <- 0
   **/
   ArrayBag();

   /**
   @return item_count_ : the current size of the bag
   **/
   int getCurrentSize() const;

   /**
   @return true if item_count_ == 0, false otherwise
   **/
   bool isEmpty() const;

   /**
   @return true if new_entry was successfully added to items_,
           false otherwise
   **/
   bool add(const ItemType& new_entry);
  
   /**
   @return true if an_entry was successfully removed from items_,
           false otherwise
   **/
   bool remove(const ItemType& an_entry);

   /**
   @post item_count_ == 0
   **/
   void clear();

   /**
   @return true if an_entry is found in items_, false otherwise
   -> THIS METHOD MUST CALL getIndexOf() <-
   **/
   bool contains(const ItemType& an_entry) const;

   /**
   @return the number of times an_entry appears in items_
   **/
   int getFrequencyOf(const ItemType& an_entry) const;

}; // end ArrayBag

#include "ArrayBag.cpp"

#endif

// end of ArrayBag.hpp

// ArrayBag.cpp

#ifndef ARRAYBAG_CPP
#define ARRAYBAG_CPP

#include "ArrayBag.hpp"

// default constructor to create an empty bag of items
template<class ItemType>
ArrayBag<ItemType>::ArrayBag(): item_count_(0) {
} // end default constructor


// function to return the number of items currently in the Bag
template<class ItemType>
int ArrayBag<ItemType>::getCurrentSize() const {
return item_count_;
} // end getCurrentSize


// function that returns true if Bag is empty else return false
template<class ItemType>
bool ArrayBag<ItemType>::isEmpty() const {
return item_count_ == 0;
} // end isEmpty


// function to add new_entry into the Bag and return true if addition is successful else return false
template<class ItemType>
bool ArrayBag<ItemType>::add(const ItemType& new_entry){

   // check if array has space
   bool hasRoomToAdd = (item_count_ < DEFAULT_CAPACITY);
   if (hasRoomToAdd) // array has space, add new_entry at the end
   {
       items_[item_count_] = new_entry;
       item_count_++;
   } // end if

   return hasRoomToAdd;
} // end add

// function to return the index of first occurrence of target in the Bag, return -1 is target is not found in Bag
template<class ItemType>
int ArrayBag<ItemType>::getIndexOf(const ItemType& target) const {

bool isFound = false;
int result = -1;

int searchIndex = 0;

// If the bag is empty, item_count_ is 0, so loop is skipped
while (!isFound && (searchIndex < item_count_))
{
       isFound = (items_[searchIndex] == target);
       if (isFound) {
           result = searchIndex;
       }
       else {
           searchIndex++;
       } // end if
   } // end while

   return result;
} // end getIndexOf


// function to remove first occurrence of an_entry from Bag and returns true if removal was successful else return false
template<class ItemType>
bool ArrayBag<ItemType>::remove(const ItemType& an_entry) {

   int locatedIndex = getIndexOf(an_entry); // get the index of first occurrence of an_entry in the bag

   // check if an_entry exist in the bag
   bool canRemoveItem = (locatedIndex > -1);
  
   // an_entry is present, replace the item with the last item of the bag
   if (canRemoveItem)   
   {
item_count_--;
items_[locatedIndex] = items_[item_count_];
   } // end if

return canRemoveItem;
} // end remove


// function to return true is an_entry is found in bag else return false
template <class ItemType>
bool ArrayBag<ItemType>::contains(const ItemType& an_entry) const {

   int locatedIndex = getIndexOf(an_entry); // get the index of first occurrence of an_entry in the bag
  
   // if an_entry exist in bag then its index > -1
   return(locatedIndex != -1);
  
} // end contains


// function to remove all the items from bag i.e set item_count_ to 0
template<class ItemType>
void ArrayBag<ItemType>::clear() {
   item_count_ = 0;
} // end clear


// function to return number of times an_entry is found in the Bag
template<class ItemType>
int ArrayBag<ItemType>::getFrequencyOf(const ItemType& an_entry) const {
  
   int frequency = 0; // initialize frequency to 0
  
   int curIndex = 0; // Current array index
   // loop over the Bag
   while (curIndex < item_count_) {
       if (items_[curIndex] == an_entry) {
           frequency++;
       } // end if
      
       curIndex++; // Increment to next entry
  
   } // end while
  
   return frequency;
} // end getFrequencyOf


#endif


// end of ArrayBag.cpp


Related Solutions

Create a class Student (in the separate c# file but in the project’s source files folder)...
Create a class Student (in the separate c# file but in the project’s source files folder) with those attributes (i.e. instance variables): Student Attribute Data type (student) id String firstName String lastName String courses Array of Course objects Student class must have 2 constructors: one default (without parameters), another with 4 parameters (for setting the instance variables listed in the above table) In addition Student class must have setter and getter methods for the 4 instance variables, and getGPA method...
In C++ 1.Create a class Point which has a template parameter of the type of internal...
In C++ 1.Create a class Point which has a template parameter of the type of internal data, T, and a template parameter for the dimension of the Point(2D, 3D etc.). Store a statically allocated, internal array of type T with dimension n. Ensure to include any constructer(s),destructors, getters or setters you might need. (10 points) 2.Create a template function which computes the Euclidean distance between 2 points. (6 points) 3.Instantiate two Point<double, 3> and compute their distance. Instantiate two Point<int,...
Create a Database from blank (scratch) for a manager and name it. Create and design a...
Create a Database from blank (scratch) for a manager and name it. Create and design a table and name it. For each fields click and choose proper a data type such as short text and name the field. Make at least three fields. Enter your records. Make sure to add your name as a record. Similarly create two more tables. By design tool, make a relationship between each of two tables at a time and drag a primary key one...
A header file contains a class template, and in that class there is a C++ string...
A header file contains a class template, and in that class there is a C++ string object. Group of answer choices(Pick one) 1)There should be a #include for the string library AND a using namespace std; in the header file. 2)There should be a #include for the string library. 3)There should be a #include for the string library AND a using namespace std; in the main program's CPP file, written before the H file's include.
c++ You will implement a template class with the following members: An array of our generic...
c++ You will implement a template class with the following members: An array of our generic type. The size of this array should be determined by an integer argument to the constructor. An integer for storing the array size. A constructor capable of accepting one integer argument. The constructor should initialize the array and set the array size. A method, find Max, that returns the maximum value in the array. A method, find Min, that returns the minimum value in...
In Java: (1) Create two files to submit: ItemToBuy.java - Class definition ShoppingCartDriver.java - Contains main()...
In Java: (1) Create two files to submit: ItemToBuy.java - Class definition ShoppingCartDriver.java - Contains main() method Build the ItemToBuy class with the following specifications: Private fields String itemName - Initialized in the nor-arg constructor to "none" int itemPrice - Initialized in default constructor to 0 int itemQuantity - Initialized in default constructor to 0 No-arg Constructor (set the String instance field to "none") Public member methods (mutators & accessors) setName() & getName() setPrice() & getPrice() setQuantity() & getQuantity() toString()...
1.) A class template can be derived from a non-template class True or False 2.) Inaccessible...
1.) A class template can be derived from a non-template class True or False 2.) Inaccessible pointer is a potential problem on simple linked list True or False 3.) Array based lists are faster in term of acing data True or False 4.) Simple linked lists use less space than double linked lists True or False 5.) For large lists "array based lists" are more efficient for insertion and deleting operational True or False 6.) We can remove data only...
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method...
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method that does the following: Prompt the user to enter a number of inches Read the number of inches entered from the console Convert the inches into an equivalent number of miles, yards, feet, and inches. Output the results to the console. For example, if a user entered 100000 inches, the program would output: 100000 inches is equivalent to: Miles: 1 Yards: 1017 Feet: 2...
C++ Static Stack Template In this chapter you studied IntStack, a class that implements a static...
C++ Static Stack Template In this chapter you studied IntStack, a class that implements a static stack of integers. Write a template that will create a static stack of any data type. Demonstrate the class with a driver program. Dynamic Stack Template In this chapter you studied DynIntStack, a class that implements a dynamic stack of integers. Write a template that will create a dynamic stack of any data type. Demonstrate the class with a driver program. Static Queue Template...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter)...
9.6 (Rational Class) Create a class called Rational (separate the files as shown in the chapter) for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private data of the class-the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should contain default values in case no initializers are provided and should store the fraction in reduced form. For...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT