Question: C++: with only iostream and std. #include using namespace std; class MyList { private: static const int DEF=10; int* a; int csz; int cap; //helper
C++: with only iostream and std.
#include
using namespace std;
class MyList
{
private:
static const int DEF=10;
int* a;
int csz;
int cap;
//helper functions
int get_index(int) const;
public:
//Already implemented functions:
MyList();
MyList(int);
~MyList();
bool add(int);
bool remove(int);
int size() const;
bool is_present(int) const;
void display() const;
//Implement the following:
//Points: 10
//This constructor will create a list of capacity cap with each element
//in the list initialized with the value initVal.
MyList(int cap, int initVal);
//Points: 10
//This function removes every occurrence of val from the list.
//Returns false if val is not in the list, true otherwise.
bool remove_all(int val);
//Points: 10
//This function swaps the contents of this list with that of other.
//The two lists may be of different size and/or capacity.
void swap(MyList* other);
//Points: 20
//This function changes the capacity of the list to newCap.
//If newCap is lesser than current cap, then the list shrinks
//and the items toward the end of the list are pruned to fit.
//If newCap is greater than the current cap, then the list needs
//to be moved to a bigger array.
//Returns false if newCap is an invalid capacity (e.g. newCap<=0),
//true otherwise.
bool change_capacity(int newCap);
};
MyList::MyList()
{
cap=DEF;
csz=0;
a=new int[cap];
}
MyList::MyList(int ucap)
{
if (ucap>0)
cap=ucap;
else
cap=DEF;
csz=0;
a=new int[cap];
}
MyList::~MyList()
{
cout << "A MyList object is being destroyed. " ;
delete[] a;
cout << "done. ";
}
bool MyList::add(int x)
{
if (csz==cap)
return false;
a[csz]=x;
csz++;
return true;
}
int MyList::size() const
{
return csz;
}
bool MyList::is_present(int x) const
{
for (int i=0;i if (a[i]==x) return true; return false; } void MyList::display() const { cout << "The list is of capacity: " << cap << endl; cout << "The current size is: " << csz << endl; cout << "Content is: "; for (int i=0;i cout << a[i] << " "; cout << endl; } bool MyList::remove(int x) { if (!is_present(x)) return false; int index=get_index(x); if (index==-1) return false; a[index]=a[csz-1]; csz--; return true; } int MyList::get_index(int x) const { if (!is_present(x)) return -1; for (int i=0;i if (a[i]==x) return i; return -1; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
