Practice test 2 answers

advertisement
COMP315 Practice Test2 – 50 Marks
Question 1
[10 Marks]
a) In order to have the file automatically compile code in that namespace scope. For
example using namespace std; allows us to write cout instead of std::cout.
b) C++ already does this by implementing == comparison operator but it's worth
knowing. Might be worth trying to write a compare that accounts for cases.
bool compare (const string& a, const string& b)
{
if(a.length() > b.length())
return false;
for(int i =0; i < a.length(); i++)
{
if(a[i] != b[i])
return false;
}
return true;
}
c) To give a header file knowledge of the expected data type or function.
d)
#ifndef
#define BALL_COUNT 5;
#endif
Question 2
a) Pure virtual functions can not be implement but can be derived from. T
class AbstractBuilding
{
public:
virtual void Build()=0;
};
b)
class Building : public AbstractBuilding
{
protected:
int size;
public:
Building(int size){this->size = size};
virtual ~Building(){};
virtual void Build();
};
c) Rectangle would have width and height.
[10 Marks]
class RectangularBuilding : public Building
{
protected:
int width;
int height;
public:
RectangularBuilding(int width, int height, int size): Building(size)
{
this->width = width;
this->height = height;
};
~RectangularBuilding(){};
void Build();
};
Question 3
double cbrt (int val)
{
return pow(val,1.0/3);
}
bool AlmostHardy(int val)
{
int i = 1;
int j = cbrt(val);
double s = 0;
while (i < j)
{
s = pow((double)i,(double)3) + pow((double)j,(double)3);
if (s == val)
return true;
else if (s < val)
i += 1;
else
j -= 1;
}
return false;
}
[10 Marks]
Question 4
[10 Marks]
bool cyclicalList()
{
Node* r = this->root;
Node* n = this->root->next;
if(n == NULL)
return false;
while (n != NULL)
{
n = n->next;
if(n == r)
return true;
}
return false;
}
void remove (string val)
{
Node* curr = root;
while (curr)
{
if(curr->next->val != NULL && curr->next->val == val)
{
Node* remove = curr->next;
Node* exchange = curr->next->next;
delete remove;
curr->next = exchange;
return;
}
curr = curr->next;
}
}
void insert(string val)
{
Node* curr = root;
while(curr)
{
curr = curr->next;
if(curr == NULL)
{
Node * n = new Node();
n->value = val;
root->next = n;
return;
}
}
}
Question 5
[10 Marks]
Note the use of reverse iterator ++it instead of it++. Your task is to find out whether it++ would
work and if it doesn't why not.
string RevNotLessThan(int L, string mstr)
{
std::vector<string> strcont;
while(mstr.find(' ') != string::npos)
{
int start = 0;
int end = mstr.find(' ');
if(end-start > L)
strcont.push_back( mstr.substr(start,end));
mstr = mstr.substr(end+1, mstr.size());
}
std::vector<string>::reverse_iterator it;
it = strcont.rbegin();
mstr.clear();
int k = strcont.size()-1;
while(it != strcont.rend())
{
mstr+= (it)->c_str();
mstr+=" ";
++it;
}
return mstr;
}
Download