CSE2050 Fall 2004 Exam #1, open book, open notes. Name ____________________ 1. True or false. Circle T or F (2 pts each) ANSWERS F Indexing an array out of bounds throws an exception. (no bounds check) T == has higher precedence than = T cout is an object. F "dog" > "cat" (comparing array addresses, not contents) F 100 / 7 * 7 == 100 (integer division drops remainder) T A pointer is a special case of an iterator. T Pass by reference is faster than pass by value. F Expressions must be passed to a function by reference. (they cannot be) T **argv == argv[0][0] T a->b == (*a).b 2. Write templated function v2m(v, m) to copy the contents of a vector v to map m such that v[i] == m[i] for all i from 0 to v.size()-1 as in this example (30 pts): vector v(5); map m; v[3] = "hi"; v2m(v, m); cout << m[3] << m.size(); // hi5 // ANSWER template void v2m(const vector& v, map& m) { for (int i=0; i m in the format "key = value", one line per pair, when the value is not "". In the above example, only the line "3 = hi" (without the quotes) would be printed. Do not assume the keys are contiguous from 0 to m.size()-1 (20 pts): // ANSWER for (map::iterator p=m.begin(); p!=m.end(); ++p) if (p->second != "") cout << p->first << " = " << p->second << endl; 4. The following templated function prints a sequence. What type of iterators does it expect? (10 pts) template void print(T b, T e) { for (int i=0; i < e-b; ++i) cout << b[i] << "\n"; } ANSWER: random access (because of e-b and b[i]) 5. Rewrite print() to accept input iterators. (20 pts) // ANSWER template void print(T b, T e) { while (b!=e) cout << *b++ << "\n"; } // OR template void print(T b, T e) { for (; b!=e; ++b) cout << *b << "\n"; }