CSE2050 Exam 1, open book, open notes. Name ____________________________ 1. Write a function, assign(), that copies a string to a vector using the copy() function. The size of the vector should be changed to match that of the string. Use the most efficient parameter passing techniques. For example (40 pts). string s="cat"; vector v(10); assign(v, s); // v[0], v[1], v[2] is 'c', 'a', 't', v.size() is 3 // Answer void assign(vector& v, const string& s) { v.resize(s.size()); copy(s.begin(), s.end(), v.begin()); } 2. Write a declaration of v that gives the same result without calling assign(), i.e. declares v and initializes it to contain a copy of the elements of s in a single statement (10 pts). // Answer vector v(s.begin(), s.end()); 3. Write code to print the elements of v (i.e. "cat") using const_iterators (10 pts). // Answer for (vector::const_iterator p=v.begin(); p!=v.end(); ++p) cout << *p; 4. Suppose that test.cpp contains the following: #include "test.h" namespace mylib { void test(int i) { if (i < 0) throw i; } } Write main.cpp, which calls test() with a negative argument, catches the exception, and prints the value thrown. Write test.h to enforce consistency with main.cpp. Show the g++ command to compile your program. (40 pts). // Answer: main.cpp #include #include "test.h" using namespace std; int main() { try { mylib::test(-1); // or add: using namespace mylib; } catch (int x) { cout << x << endl; } return 0; } // test.h namespace mylib { void test(int); } // To compile: g++ main.cpp test.cpp