Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A bag can contain more than one copy of an item. For example, the chapter descri

ID: 3663897 • Letter: A

Question

A bag can contain more than one copy of an item. For example, the chapter describes a bag that contains the number 4 and two copies of the number 8. This bag behavior is different from a set, which can contain only a single copy of any given item. Write a new container class called set, which is similar to a bag, except that a set can contain only one copy of any given item. You’ll need to change the interface a bit. For example, instead of the bag’s count function, you’ll want a constant member function such as this:

bool set::contains
(const value_type& target) const;
// Postcondition: The return value is true if // target is in the set; otherwise the return // value is false.

Make an explicit statement of the invariant of the set class. Do a time analysis for each operation. At this point, an efficient implementation is not needed. For example, just adding a new item to a set will take linear time because you’ll need to check that the new item isn’t already present. Later we’ll explore more efficient implementations (including the implementation of set in the C++ Standard Library).

You may also want to add additional operations to your set class, such as an operator for subtraction.

Explanation / Answer

-----------------------------------.h #ifndef SET_H #define SET_H #include class set { public: static const size_t CAPACITY = 30; typedef int Item; set(){used=0;} void insert(const Item& target); void remove(const Item& target); size_t size() const {return used;}; bool contains(const Item& target)const; void display(); private: Item data[CAPACITY]; size_t used; }; #endif #include #include #include #include "set.h" void set::insert(const Item& entry) { assert(size() < CAPACITY); //set::const; if(contains(entry==false)) { data[used] = entry; used++; } } bool set::contains(const Item& target)const { for(int i = 0;i < used;i++ ) { if(data[i]==target) return true; } return false; } void set::display() { if(used==0) { cout<<"The bag is empty."<<endl; } else{ for(size_t i=0; i<used;> cout<<data[i]<<" "; } #include #include #include "SET.h" #include "set.cpp" int main() { set i; //int i; cout<< "enter a number:"; cin>>i; //for(i=0; i < used; i++) //if(target == data[i]) //i++; set.insert(i); set display(); getch(); return 0; }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote