C++ language A bag can contain more than one copy of an item. For example, the c
ID: 3855289 • Letter: C
Question
C++ language
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 cop- ies 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 any given item. You'll need to change the interface a bit. For example, n- stead of the bag's count function, you'll want a con- contain only one copy of stant member function such as this: bool set::contains (const value type& target) const; /I Postcondition: The return value is true if // target is in the set; otherwise the return /I value is false. Make an explicit statement of the invariant of the set class. Do a time analysis for each operation. At thisExplanation / Answer
#include <bits/stdc++.h>
using namespace std;
class Myset
{
int val;
vector<int> v;
public:
void insert(int x)
{
if(contains(x))
{
cout<<"Cannot contains duplicates ";
}
else
{
v.push_back(x);
cout<<x<<"is inserted ";
}
}
bool contains(int x)
{
if(std::find(v.begin(), v.end(), x) != v.end()) {
return true;
} else {
return false;}
}
void PrintSet()
{
for (std::vector<int>::const_iterator i = v.begin(); i != v.end(); ++i)
cout << *i << " ";
}
};
int main(int argc, char const *argv[])
{
Myset s;
s.insert(2);
s.insert(3);
s.insert(3);
s.PrintSet();
return 0;
}
==========================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ set.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
2is inserted
3is inserted
Cannot contains duplicates
2 3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.