CSE390C Key to Sample Final, Spring 2022 handout #8
1. Statement Output
------------------------------------------------------------
var1->f1(); mumble 1
var2->f1(); mumble 1
var3->f1(); foo 1
var4->f1(); baz 1
var5->f1(); baz 1
var1->f2(); foo 2
var2->f2(); mumble 2
var3->f2(); foo 2
var4->f2(); foo 2
var5->f2(); baz 2
var1->f3(); foo 3
var2->f3(); baz 3
var3->f3(); foo 3
var4->f3(); foo 3
var5->f3(); baz 3
2. One possible solution appears below.
class point {
public:
point(int x = 0, int y = 0) : x(new int(x)), y(new int(y)) { }
point(const point & rhs) {
x = new int(*rhs.x);
y = new int(*rhs.y);
}
~point() {
delete x;
delete y;
}
point & operator=(const point & rhs) {
if (this != &rhs) {
*x = *rhs.x;
*y = *rhs.y;
}
return *this;
}
int get_x() const {
return *x;
}
int get_y() const {
return *y;
}
void set_location(int new_x, int new_y) {
*x = new_x;
*y = new_y;
}
private:
int * x;
int * y;
};
3. One possible solution appears below.
void remove_3s(set & s) {
auto itr = s.begin();
while (itr != s.end()) {
if (*itr % 3 == 0) {
itr = s.erase(itr);
} else {
itr++;
}
}
}
4. One possible solution appears below.
map> string_indexes(const vector & data) {
map> result;
for (int i = 0; i < data.size(); i++) {
result[data[i]].insert(i);
}
return result;
}
5. One possible solution appears below.
void sort_reverse(vector & v) {
auto middle = v.begin() + (v.size() + 1) / 2;
sort(v.begin(), middle);
reverse(middle, v.end());
}
6. One possible solution appears below.
class sequence {
public:
sequence(int d) : empty(d) { }
virtual ~sequence() { }
void add(int n) {
data.push_back(n);
}
virtual int f(int a, int b) const = 0;
int reduce() const {
if (data.size() == 0)
return empty;
else {
int result = data[0];
for (int i = 1; i < data.size(); i++) {
result = f(result, data[i]);
}
return result;
}
}
private:
vector data;
int empty;
};
class sum : public sequence {
public:
sum() : sequence(0) { }
int f(int a, int b) const {
return a + b;
}
};
7. The function is returning a reference to a local variable. This won't work
properly because local variables are stack-allocated and after a function
finishes executing, the memory allocated for this variable is released when
we pop the stack. The compiler won't allow you to make a reference to
memory that is no longer being used.