CSE2050 Spr. 2003 Exam #2, open books, open notes. Name ________________ 1. (15 pts). Write a templated function that takes 2 INPUT iterators pointing to the beginning and end of a sequence and returns the size of the sequence as an int. For example: list x(5); cout << length(x.begin(), x.end()); // 5 // ANSWER (other solutions are possible) template int length(T begin, T end) { int size=0; while (begin != end) { ++begin; ++size; } return size; } 2. (10 pts). Rewrite the code in length() (just what's inside the {braces} ) to execute in O(1) time using random iterators. // ANSWER return end - begin; 3. (75 pts). Write a class Number that can be initialized either from a double or a string representation of a double (e.g. 3.2 or "3.2"). Write an accessor method to return the value as a double. Write operator + as a non-member to add two Numbers and return Number. Write operator << to output a Number. Use constructor initialization, const methods, and appropriate parameter passing. Show at least one member function not inlined. For example: Number a=3, b("4.5"); cout << a+b << endl; // 7.5 cout << (a+"1").value(); // 4.0 // ANSWER class Number { private: double num; // Name it whatever you want public: Number(double n): num(n) {} // preferred over {num=n;} Number(const string&); // Pass string by const reference double value() const {return num;} // Don't forget const }; // This one is not inlined (you have your choice) Number::Number(const string& s): num(atof(s.c_str())) {} // Not a member (read problem) Number operator+(const Number& a, const Number& b) { return Number(a.value()+b.value()); // Or return a.value()+b.value(); } // Not a member (ever) ostream& operator << (ostream& out, const Number& b) { out << b.value(); return out; }