CSE390C Key to Sample Final, Winter 2024 handout #8
1. Statement Output
------------------------------------------------------------
var1->f1(); foo 1
var2->f1(); mumble 1
var3->f1(); mumble 1
var4->f1(); foo 1
var5->f1(); baz 1
var1->f2(); mumble 2
var2->f2(); mumble 2
var3->f2(); mumble 2
var4->f2(); foo 2
var5->f2(); foo 2
var1->f3(); foo 3
var2->f3(); bar 3
var3->f3(); mumble 3
var4->f3(); foo 3
var5->f3(); bar 3
2. One possible solution appears below.
class string_pair {
public:
string_pair(const string & one = "", const string & two = "")
: first(new string(one)), second(new string(two)) { }
string_pair(const string_pair & rhs) {
first = new string(*rhs.first);
second = new string(*rhs.second);
}
~string_pair() {
delete first;
delete second;
}
string_pair & operator=(const string_pair & rhs) {
if (this != &rhs) {
*first = *rhs.first;
*second = *rhs.second;
}
return *this;
}
const string & get_first() const {
return *first;
}
const string & get_second() const {
return *second;
}
string to_string() {
return "(" + *first + ", " + *second + ")";
}
private:
string * first;
string * second;
};
3. One possible solution appears below.
void retain_all(set & s1, const set & s2) {
auto itr = s1.begin();
while (itr != s1.end()) {
if (find(s2.begin(), s2.end(), *itr) == s2.end()) {
itr = s1.erase(itr);
} else {
itr++;
}
}
}
4. One possible solution appears below.
map> convert(const set & numbers) {
map> result;
for (const string & s : numbers) {
result[s.substr(0, 3)].insert(s.substr(4));
}
return result;
}
5. One possible solution appears below.
int count_shuffles(vector & v) {
int count = 0;
while (!is_sorted(v.begin(), v.begin() + (v.size() + 1) / 2)) {
count++;
random_shuffle(v.begin(), v.end());
}
return count;
}
6. One possible solution appears below.
class printable {
public:
virtual void print(ostream & out) const = 0;
virtual ~printable() { }
};
ostream & operator<<(ostream & out, const printable & value) {
value.print(out);
return out;
}
class quoted_text : public printable {
public:
quoted_text(const string & s) : text(s) {}
void print(ostream & out) const {
out << "'" << text << "'";
}
private:
string text;
};
7. If the variable data is declared to be a const reference, then the second
version of the foreach loop wouldn't compile because it "discards
qualifiers" (as the compiler says). This would also fail if there is only a
const version of the iterator for the given structure, as is true for a
set. Yet another reason it could fail is if data is an instance
variable for a class and this code appears in a const member function.