CSE2050 Fall 03 Exam #1, open book, open notes. Name ____________________ 1. Which of the following statements are legal? Circle OK if the statement will compile, or ERROR if not. (4 pts each). const string cs("abc"); OK string s = cs; OK cs = s; ERROR (assignment to const) string::const_iterator cp = s.begin(); OK string::iterator p = cs.begin(); ERROR (non-const iterator pointing to const element) cp = p; OK p = cp; ERROR (non-const iterator pointing to const element) *cp = *p; ERROR (assignment to const) *p = *cp; OK ++cp; OK 2. Write code to copy a into v using the copy() function (10 pts). int a[10]; vector v(10); // ANSWER copy(a, a+10, v.begin()); 3. The function f(s1, s2) takes a string s1, does something, and assigns a result to string s2. Sometimes it runs out of memory and throws an exception of type bad_alloc. Write an equivalent function safe_f(s1, s2) that behaves like f, except that if it runs out of memory it assigns an empty string ("") to s2 instead of throwing an exception. Use the most efficient form of parameter passing. (25 pts). // ANSWER void safe_f(const string& s1, string& s2) { try { f(s1, s2); } catch (bad_alloc x) { // Names other than x are acceptable s2 = ""; } } 4. Write code to print the contents of m, a map >. Each map element should be on one line, with the key and list of values separated by spaces, e.g. (25 pts.) map > m; m[8].push_back("cat"); m[5].push_back("horse"); m[5].push_front("cart"); Your code would print 5 cart horse 8 cat // ANSWER for (map >::const_iterator p=m.begin(); p!=m.end(); ++p) { cout << p->first; for (list::const_iterator q=p->second.begin(); q!=p->second.end(); ++q) cout << " " << *q; cout << endl; // or "\n" or '\n' } // Names other than p and q are acceptable. // You may also use iterator instead of const_iterator unless you wrote // a function and passed m by const reference.