Please, need this code in C++ A bag can contain more than one copy of an item. F
ID: 668686 • Letter: P
Question
Please, need this code in C++
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 nnumber 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 ser, 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 funtion, you'll want a constant member function suich as this:
bool set:: contains
(const value_type& target) const;
//Postcondition: The return balue 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 efficiemt implementation is not needed. For example, just adding a new item to a set will take linear time becauseyou'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++ Stadard Library.
You may also want to add additional operations to your set class, such as an operator for subtraction.
Use C++ and please create 3 file incuding header file
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
SET.H FILE
class set{
public:
// LinkedList to contain the element in the bag
vector<int> my_vec;
bool contains(int n);
int search(int n);
void add(int n);
void remove(int n);
};
int set::search(int n){
for (int i = 0; i < my_vec.size(); i++){
if (my_vec[i] == n) return i;
}
return -1;
}
void set::add(int n){
my_vec.push_back(n);
}
void set::remove(int n){
int res = search(n);
if (res != -1)
my_vec.erase(my_vec.begin()+res,my_vec.begin()+res+1);
}
bool set::contains(int n){
int count = 0;
for (int i = 0; i < my_vec.size(); i++){
if (my_vec[i] == n)
count++;
}
if (count >= 2) return true;
return false;
}
MAIN.CPP FILE
int main() {
int n;
set *s = new set();
while (true){
cout << "Enter a Number : ";
cin >> n;
if(s->contains(n) == true)
cout << "There is already a code of this number, so can not add it " << endl;
else{
s->add(n);
}
}
return 0;
}