CSE2050 Spr. 2004 Exam #2, open book, open notes. Name ___________________ 1. Overload << as a template to print a map where K and V are any types that can also be printed with <<. Each key-value pair should be printed on one line separated by a space, e.g, (30 pts). map m1; // Prints the following: m1["xyz"]=m1["abc"]=4; // map m2; // abc 4 m2[2.5]='z'; // xyz 4 cout << m1 << m2; // 2.5 z // ANSWER template ostream& operator << (ostream& out, const map& m) { for (map::const_iterator p=m.begin(); p!=m.end(); ++p) out << p->first << ' ' << p->second << '\n'; return out; } 2. A String behaves like std::string and has the implementation shown below. Add the three functions required by the rule of 3 (30 pts). Write size() (5 pts). Write const and non-const versions of operator[] (10 pts). Define iterator and const_iterator as pointer types (10 pts) and write const and non-const versions of begin() and end() (15 pts). class String { char* p; // NUL terminated array public: String(const char* s=""): p(new char[strlen(s)+1]) { copy(s, s+strlen(s)+1, p); } const char* c_str() const {return p;} // ANSWER // Rule of 3 ~String() {delete[] p;} // destructor String(const String& s): p(new char[strlen(s.p)+1]) { // copy constructor copy(s.p, s.p+strlen(s.p)+1, p); // or copy as below } String& operator = (const String& s) { // assignment may change size if (this != &s) { delete[] p; p = new char[s.size()+1]; // allow for '\0' at end copy(s.p, s.p+s.size()+1, p); // or s.begin(), s.end()+1 } return *this; } // Size does not include \0 at end int size() const {return strlen(p);} // Index char& operator[](int i) {return p[i];} char operator[](int i) const {return p[i];} // or return const char& // Iterator types typedef char* iterator; typedef const char* const_iterator; // begin(), end() iterator begin() {return p;} const_iterator begin() const {return p;} iterator end() {return p+size();} // or p+strlen(p), do not include \0 const_iterator end() const {return p+size();} };