CSE2050 Exam #1. Open books, open notes
Name _______________________________________________________
1. (35 pts). Write a function repeat(s, n) that takes a string s
and changes it to a concatenation of n copies of s. For example:
string s = "hello";
repeat(s, 3);
cout << s << endl; // hellohellohello
void repeat(string& s, int n) {
string t;
for (int i=0; i<n; ++i)
t += s;
s = t;
}
Other variations are possible. I deducted 4 points if s was
not passed by reference, 4 if the logic was wrong (an extra variable
is needed), 2 if you returned something. The function should
not print anything.
2. (15 pts). The following function is supposed to print the middle
element of a vector<int> (or just to the right of the middle if the
size is even), given the beginning and ending iterators.
void print_middle(vector<int>::const_iterator begin,
vector<int>::const_iterator end) {
if (begin == end)
throw domain_error("middle of empty vector");
cout << *((begin + end)/2); // Error
}
The function does not compile because iterators cannot be added to
each other or divided. The only allowable arithmetic operations
are addition or subtraction of an int to get another iterator
(begin + 1, end - 3), or subtraction of two iterators to get an
int (int size = end - begin;). Rewrite the last statement to
correct this error.
cout << *(begin + (end - begin)/2);
or
cout << begin[(end - begin)/2];
3. (15 pts). Write a header file print_middle.h that would allow
print_middle() to be compiled separately from the rest of the program.
#ifndef GUARD_print_middle_h
#define GUARD_print_middle_h
#include <vector>
void print_middle(std::vector<int>::const_iterator begin,
std::vector<int>::const_iterator end);
#endif
The #ifndef...#endif statements are optional. I took off
2 points if you used a using statement instead of std::
I took off 6 if you put the code in the header file.
4. (35 pts.) Write a main() function to include your header file
and test print_middle() by printing the middle element of a vector.
Demonstrate catching the exception by passing an empty slice of the
same vector.
#include <iostream>
#include <vector>
#include <stdexcept>
#include "print_middle.h"
using namespace std;
int main() {
vector<int> v(5);
try {
print_vector(v.begin(), v.end());
print_vector(v.begin(), v.begin()); // Empty
}
catch (domain_error e) {
cout << "Empty vector\n";
}
return 0;
}
I took off 8 points if you forgot the try...catch block.
There are various ways to put elements in the vector such
as using v.push_back() or v.resize().