CSE390C Key to Final, Spring 2025 handout #9 1. Statement Output ------------------------------------------------------------ var1->f1(); foo 1 var2->f1(); foo 1 var3->f1(); bar 1 var4->f1(); baz 1 var5->f1(); mumble 1 var1->f2(); foo 2 var2->f2(); foo 2 var3->f2(); baz 2 var4->f2(); baz 2 var5->f2(); mumble 2 var1->f3(); baz 3 var2->f3(); mumble 3 var3->f3(); baz 3 var4->f3(); baz 3 var5->f3(); mumble 3 2. One possible solution appears below. class int_list { public: int_list() { // nothing to do } int_list(const int_list & rhs) { for (int * p : rhs.values) { values.push_back(new int(*p)); } } ~int_list() { for (int * p : values) { delete p; } } int_list & operator=(const int_list & rhs) { if (this != &rhs) { for (int * p : values) { delete p; } values.clear(); for (int * p : rhs.values) { values.push_back(new int(*p)); } } return *this; } int size() const { return values.size(); } int get(int index) const { return *(values[index]); } void add(int value) { values.push_back(new int(value)); } private: vector<int *> values; }; 3. One possible solution appears below. class int_comparable { public: virtual int value() const = 0; virtual ~int_comparable() { } }; bool operator<(const int_comparable & lhs, const int_comparable & rhs) { return lhs.value() < rhs.value(); } class manhattan_point : public int_comparable { public: manhattan_point(int x = 0, int y = 0) : x(x), y(y) { // nothing else to do } int value() const { return x + y; } private: int x, y; }; 4. One possible solution appears below. string acronym_for(const vector<string> & words) { string result; for (const string & s : words) { result += toupper(s[0]); } return result; } 5. One possible solution appears below. int record_date(map<string, list<string>> & dates, const string & name1, const string & name2) { dates[name1].push_front(name2); dates[name2].push_front(name1); return count(dates[name1].begin(), dates[name1].end(), name2); } 6. Two possible solutions appear below. int random_pairwise_sorted(vector<int> data) { random_shuffle(data.begin(), data.end()); int count = 0; for (int i = 0; i < data.size() - 1; i++) { if (data[i] <= data[i + 1]) { count++; } } return count; } int random_pairwise_sorted(vector<int> data) { random_shuffle(data.begin(), data.end()); cout << "numbers = " << to_string(data) << endl; int count = 0; auto itr = data.begin(); while (itr + 1 != data.end()) { if (is_sorted(itr, itr + 2)) { count++; } itr++; } return count; } 7. We expect to be able to chain together several assignment operations and that would no longer compile, as in: string s1 = "hello"; string s2, s3; s2 = s3 = s1; Because the return type of the assignment operator is a reference and not a const reference, we would also expect to be able to write odd code like this: string s4 = "foo"; (s1 = s4)[0] = '#'; This would set s1 to "#oo" instead of "foo".
Stuart Reges
Last modified: Fri Jun 13 09:53:17 PDT 2025