COMP2004 Programming Practice
2002 Summer School

Week 6 Wednesday Tutorial Exercises


  1. Modify your template functions from Question 3 of the Week 4 Wednesday tutorial so that their third element is an output iterator, rather than an ostream&. For example,
    template <typename II, typename OI>
    double_copy(II begin, II end, OI out);
    

  2. Test the above template functions using ostream_iterator, eg;
    int main() {
    	vector<int> v;
    	for (int i = 1; i <= 10; ++i)
    		v.push_back(i);
    	double_copy(v.begin(), v.end(), ostream_iterator(cout, "\n"));
    }
    

  3. Test the above template functions using container output iterators, eg;
    int main() {
    	vector<int> v;
    	for (int i = 1; i <= 10; ++i)
    		v.push_back(i);
    	list<int> l;
    	double_copy(v.begin(), v.end(), back_inserter(l));
    	copy(l.begin(), l.end(), ostream_iterator<int>(cout, "\n"));
    }
    

  4. UPDATE: In fact, the templated function as shown below is not possible. Refer to the tutorial solutions to find out why and how to fix it.

    Write the contents of the following templated function which compares two objects with a particular comparator (binary predicate):

    template <typename T>
    void check(const T& a, const binary_function<T, T, bool>& comp, const T& b);
    
    The function should output "Comparison is true" or "Comparison is false" to cout. You can use this main program to test it.
    int main() {
    	check(3, less<int>(), 4);
    	check(3, greater_equal_to<int>(), 4);
    	check("abc", equal_to<string>(), "acd");
    	check(true, logical_or<bool>(), false);
    }
    
    Notice that all of the binary predicate classes (ie. less, greater_equal_to, equal_to, logical_or, etc) inherit from the binary_function class. The binary_function class is templated based on the type of the first argument, the type of the second argument, and the return type. Since binary predicates always compare two arguments of the same type and return a bool, the 2nd parameter to the check() function is defined as
    const binary_function<T, T, bool>& comp
    
    For example, the equal_to class is defined as
    template <typename T>
    struct equal_to : public binary_function<T, T, bool> {
    	bool operator()(const T& x, const T& y) const {
    		return (x == y);
    	}
    };