template <typename II, typename OI> double_copy(II begin, II end, OI out);
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")); }
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")); }
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>& compFor 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); } };