Question

C++ Class involving difference. The goal is to overload the function: void Bag::operator-=(const Bag& a_bag) //...

C++ Class involving difference.

The goal is to overload the function:

void Bag::operator-=(const Bag& a_bag)

// The Set Difference between two sets A and B is the set that consists of the elements of A which are not elements of B. Bag bag1 = (1,2,3) and Bag bag2 = (2,4,5) then bag1-=bag2 should return 1,3,4,5.

//parameter a_bag to be subtracted from this (the calling) bag

//post removes all data from items_ that is also found in a_bag

//Since type is void, it should not return an array.

#include <iostream>
#include <string>

#include <vector>

using namespace std;

template
class Bag
{
public:
    Bag();
    int getCurrentSize() const;
    bool isEmpty() const;
    bool add(const T& new_entry);
    bool remove(const T& an_entry);
    /**
     @post item_count_ == 0
     **/
    void clear();
    /**
     @return true if an_etry is found in items_, false otherwise
     **/
    bool contains(const T& an_entry) const;

    /**
     @return the number of times an_entry is found in items_
     **/
    int getFrequencyOf(const T& an_entry) const;

    /**
     @return a vector having the same cotntents as items_
     **/
    std::vector toVector() const;

    void display() const;  // displays the output 

    void operator-=(const Bag& a_bag); //DO NOT CHANGE RETURN TYPE

protected:
    static const int DEFAULT_CAPACITY = 200;  //max size of items_
    T items_[DEFAULT_CAPACITY];              // Array of bag items
    int item_count_;                         // Current count of bag items
    int getIndexOf(const T& target) const;


};
template
Bag::Bag(): item_count_(0)
{
}  // end default constructor

template
int Bag::getCurrentSize() const
{
    return item_count_;
}  // end getCurrentSize

template
bool Bag::isEmpty() const
{
    return item_count_ == 0;
}  // end isEmpty


template
bool Bag::add(const T& new_entry)
{
    bool has_room = (item_count_ < DEFAULT_CAPACITY);
    //bool notDup = items_.getFrequencyOf(new_entry) == 0; 
    if (has_room) //&& notDup) 
    {
        items_[item_count_] = new_entry;
        item_count_++;
        return true;
    }  // end if

    return false;
}  // end add

template
void Bag::display() const {
    for(int x = 0; x < item_count_;x++)
        cout << items_[x] << ", "; 
}


/**
 @return true if an_entry was successfully removed from items_, false otherwise
 **/
template
bool Bag::remove(const T& an_entry)
{
   int found_index = getIndexOf(an_entry);
    bool can_remove = !isEmpty() && (found_index > -1);
    if (can_remove)
    {
        item_count_--;
        items_[found_index] = items_[item_count_];
    }  // end if

    return can_remove;
}  // end remove


/**
 @post item_count_ == 0
 **/
template
void Bag::clear()
{
    item_count_ = 0;
}  // end clear

template
int Bag::getFrequencyOf(const T& an_entry) const
{
   int frequency = 0;
   int cun_index = 0;       // Current array index
   while (cun_index < item_count_)
   {
      if (items_[cun_index] == an_entry)
      {
         frequency++;
      }  // end if

      cun_index++;          // Increment to next entry
   }  // end while

   return frequency;
}  // end getFrequencyOf

template
bool Bag::contains(const T& an_entry) const
{
    return getIndexOf(an_entry) > -1;
}  // end contains

template
std::vector Bag::toVector() const
{
   std::vector bag_contents;
    for (int i = 0; i < item_count_; i++)
        bag_contents.push_back(items_[i]);

   return bag_contents;
}  // end toVector
template
void Bag::operator-=(const Bag& a_bag)

{}

Homework Answers

Answer #1
template
void Bag::operator-=(const Bag& a_bag){
    
    for(int i=item_count_; i>=0; i--) {
        T x = items_[i];
        
        if(a_bag.contains(x)) {
            remove(x);
        } else {
            add(x);
        }
    }
    
}
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h"...
- implement the Stack ADT using the linked list approach. Use C++ program language #include "StackLinked.h" template StackLinked::StackLinked (int maxNumber) { } template StackLinked::StackLinked(const StackLinked& other) { } template StackLinked& StackLinked::operator=(const StackLinked& other) { } template StackLinked::~StackLinked() {    clear(); } template void StackLinked::push(const DataType& newDataItem) throw (logic_error) {    } template DataType StackLinked::pop() throw (logic_error) { } template void StackLinked::clear() {    StackNode* t;    while ( top != NULL)    {        t = top;       ...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template...
Data Structures using C++ Consider the classes QueueADT and ArrayQueueType: QueueADT: #ifndef QUEUEADT_H #define QUEUEADT_H template <class ItemType> class QueueADT { public:        // Action responsibilities        virtual void resetQueue() = 0;           // Reset the queue to an empty queue.           // Post: Queue is empty.        virtual void add(const ItemType& newItem) = 0;           // Function to add newItem to the queue.           // Pre: The queue exists and is not full.          ...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input...
Using the following code perform ALL of the tasks below in C++: ------------------------------------------------------------------------------------------------------------------------------------------- Implementation: Overload input operator>> a bigint in the following manner: Read in any number of digits [0-9] until a semi colon ";" is encountered. The number may span over multiple lines. You can assume the input is valid. Overload the operator+ so that it adds two bigint together. Overload the subscript operator[]. It should return the i-th digit, where i is the 10^i position. So the first...
Something is either messed up in my operator overload <<, covertopostfix function, or my main output....
Something is either messed up in my operator overload <<, covertopostfix function, or my main output. Cannot figure it out. please help. Please comment your changes too. Program below is supposed to be outputting like this: InFix is:   A+B-C Post fix is:   A B + C - InFix is:   A+C Post fix is:   A C + InFix is:   x*(y+z)-(w+t) Post fix is:   x y z + * w t + - InFix is:   A+B*(C+D)-E/F+G+H Post fix is:   A B C...
#ifndef BAG_H #define BAG_H #include <cstdlib> // Provides size_t using namespace std; class bag { public:...
#ifndef BAG_H #define BAG_H #include <cstdlib> // Provides size_t using namespace std; class bag { public: // TYPEDEFS and MEMBER CONSTANTS typedef int value_type; typedef std::size_t size_type; static const size_type CAPACITY = 30; // CONSTRUCTOR bag() {used = 0;} // MODIFICATION MEMBER FUNCTIONS size_type erase(const value_type& target); bool erase_one(const value_type& target); void insert(const value_type& entry); void operator +=(const bag& addend); void sort(const bag& b); //Sort the array in the bag object // CONSTANT MEMBER FUNCTIONS size_type size( ) const {...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>...
Data Structures using C++ Consider the following class #ifndef LINKEDQUEUETYPE_H #define LINKEDQUEUETYPE_H #include <iostream> #include <new>    #include <cstdlib> #include "QueueADT.h" using namespace std; // Definition of the node template <class ItemType> struct NodeType {        ItemType info;        NodeType<ItemType> *next; }; template <class ItemType> class LinkedQueueType: public QueueADT<ItemType> { public:        // Constructor        LinkedQueueType();           // Default constructor.           // Post: An empty queue has been created. queueFront = NULL;           //       queueBack = NULL;...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in...
Getting the following errors: Error 1 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 565 Error 2 error C2436: '{ctor}' : member function or nested class in constructor initializer list on line 761 I need this code to COMPILE and RUN, but I cannot get rid of this error. Please Help!! #include #include #include #include using namespace std; enum contactGroupType {// used in extPersonType FAMILY, FRIEND, BUSINESS, UNFILLED }; class addressType { private:...
could you implement this function please, im having issues with it. void makeList (const ListNode::value_type [],const...
could you implement this function please, im having issues with it. void makeList (const ListNode::value_type [],const size_t& count) class ListNode { public: typedef int value_type; ListNode (value_type d = value_type(), ListNode* n = NULL) { datum = d; next = n; }    //Assessor value_type getDatum () const { return datum; } ListNode const* getNext () const { return next; }    //Mutator void setDatum (const value_type& d) {datum = d; } ListNode* getNext () { return next; } void...
C++ See the provided specification files. Complete the implementation for each as a separate file. void...
C++ See the provided specification files. Complete the implementation for each as a separate file. void seen(std::string); If there is already a Word object in the Words list, then the number of occurrences for this word is incremented. If there is no Word object for this word already, create a new word object with occurrence =1, and insert this object into the list of Word objects. std::string getNextWord(); Returns the next word of the list and sets the currentItem pointer...
this is the book name. Data Structures and Abstractions with Java 1) Description: The sample programs...
this is the book name. Data Structures and Abstractions with Java 1) Description: The sample programs in Chapter 1 of your textbook are not complete. They are used for illustration purpose only. The implementation of Listing 1-1 on page 39 is explained in Chapter 2. And, in order to see the result of using it, we will need the following set of files: i. BagInteface.java – the specification only. ii. ArrayBag.java – the implementation of BagInerface.java. iii. ArrayBagDemo.java – a...